[Swift 기본 문법] struct,class, enum

dora·2024년 3월 12일

Swift 기본 문법

목록 보기
4/12

Struct

C언어의 구조체보다 다양한 기능을 가진다.
swift의 대부분의 타입이 구조체로 이루어져 있을 정도로 중요하다.

  • 연관된 몇몇 값들을 모아서 하나의 데이터 타입으로 표현하고 싶을 때
  • 다른 객체 또는 함수 등으로 전달될 때(즉, 참조가 아닌 복사를 원할 때)
  • 자신을 상속할 필요가 없거나 자신이 다른 타입을 상속받을 필요가 없을 때
struct Sample{
    var mutableProperty: Int = 100  // 가변 프로퍼티
    let immutableProperty: Int = 100    // 불변 프로퍼티
    
    static var typeProperty: Int = 100  // 타입 프로퍼티
    
    //인스턴스 메서드 : 구조체 안에 들어있는 함수
    func instanceMethod(){
        print("instance method")
    }
    
    //타입 메서드 :
    static func typeMethod() {
        print("type method")
    }
}

//가변 인스턴스
var mutable : Sample = Sample()

mutable.mutableProperty = 200
//mutable.immutableProperty = 200

//불변 인스턴스
let immutable: Sample = Sample()

//mutable.mutableProperty = 200
//mutable.immutableProperty = 200

//타입 프로퍼티 및 메서드
Sample.typeProperty = 300
Sample.typeMethod()     // type method

//mutable.typeProperty = 400
//mutable.typeMethod()

예시

struct Student{
    var name: String = "unknown"
    var `class`: String = "Swift"   //다른 곳에 키워드로 쓰이고 있기 때문이 ``으로 묶어준다.
    
    static func selfIntroduce(){
        print("학생타입 입니다")
    }
    
    func selfIntroduce() {
        print("저는 \(self.class)\(name)입니다")
    }
}

Student.selfIntroduce() //학생타입입니다

var dora : Student = Student()
dora.name = "dora"
dora.class = "스위프트"
dora.selfIntroduce()


let jina : Student = Student()

// 불변 인스턴스이므로 프로퍼티 값 변경 불가
// 컴파일 오류 발생

//jina.name = "jina"
jina.selfIntroduce()   // 저는 Swift반 unknown입니다

Class

다중 상속을 지원하지 않으며, struct와 달리 참조 타입이다.

class Sample{
    var mutableProperty: Int = 100  //가변 프로퍼티
    let immutableProperty: Int = 100    // 불변 프로퍼티
    
    static var typeProperty: Int = 100  // 타입 프로퍼티
    
    //인스턴스 메서드
    func instanceMethod() {
        print("instance method")
    }
    
    //타입 메서드(2)
    //상속 받았을 때, 재정의 불가 타입 메서드 - static
    static func typeMethod(){
        print("type method - static")
    }
    
    //재정의 가능 타입 메서드 - class
    class func classMethod(){
        print("type method - class")
    }
}

var mutableReference: Sample = Sample()

mutableReference.mutableProperty = 200
//mutableReference.immutableProperty = 200

let immutableReference: Sample = Sample()

immutableReference.mutableProperty = 200
//immutableReference.immutableProperty = 200

//immutableReference = mutableReference

//타입 프로퍼티 및 메서드
Sample.typeProperty = 300
Sample.typeMethod() //type method

//mutableReference.typeProperty = 400
//mutableReference.typeMethod()

예시

class Student{
    var name: String = "unknown"
    var `class`: String = "Swift"
    
    class func selfIntroduce(){
        print("학생타입 입니다")
    }
    
    func selfIntroduce(){
        print("저는 \(self.class)\(name)입니다")
    }
}

Student.selfIntroduce()

var dora : Student = Student()
dora.name = "dora"
dora.class = "스위프트"
dora.selfIntroduce()

let jina: Student = Student()
jina.name = "jina"
jina.selfIntroduce()

Enum

swift의 enum은 다른 언어에서의 열거형과 달리 강력한 기능을 한다.

enum Weekday{
    case mon
    case tue
    case wed
    case thu, fri,sat,sun
}

var day: Weekday = Weekday.mon
day = .tue

print(day)

switch day{
case .mon, .tue, .wed, .thu:
    print("평일입니다")
case Weekday.fri:
    print("불금입니다")
case .sat, .sun:
    print("신나는 주말!!")
}

정수 타입이나, Hashable의 프로토콜을 따르는 모든 타입이 원시값의 타입으로 지정될 수 있다

enum Fruit: Int{
    case apple = 0
    case grape = 1
    case peach
}

print("Fruit.peach.rawValue == \(Fruit.peach.rawValue)")

enum School: String {
    case elementary = "초등"
    case middle = "중등"
    case high = "고등"
    case university
}

print("School.middle.rawValue == \(School.middle.rawValue)")
//School.middle.rawValue == 중등

print("School.university.rawValue == \(School.university.rawValue)")
//School.middle.rawValue == university

let apple: Fruit? = Fruit(rawValue: 0)

rawValue를 통해 초기화할 수 있으며 case에 해당하지 않을 수 있으므로 옵셔널 타입이다.


if let orange: Fruit = Fruit(rawValue: 5){
    print("rawValue 5에 해당하는 케이스는 \(orange)입니다")
} else{
    print("rawValue 5에 해당하는 케이스가 없습니다")
}

enum내에서 메서드 또한 추가할 수 있다

enum Month{
    case dec, jan, feb
    case mar, apr, may
    case jun, jul, aug
    case sep, oct, nov
    
    func printMessage(){
        switch self{
        case .mar, .apr, .may:
            print("따스한 봄~")
        case .jun, .jul, .aug:
            print("여름은 더워요~")
        case .sep, .oct, .nov:
            print("가을은 독서의 계절!")
        case .dec, .jan, .feb:
            print("추운 겨울입니다")
        }
}
    
Month.mar.printMessage()

Value & Reference

structClassEnum
typeReferenceValueValue
SubclassingOXX
ExtensionOOO

swift는 구조체와 열거형 사용을 선호한다.
apple의 프레임 워크는 대부분 클래스를 사용한다

import Swift

struct ValueType{
    var property = 1
}

class ReferenceType{
    var property = 1
}

let firstStructInstance = ValueType()
var secondStructInstace = firstStructInstance
secondStructInstace.property = 2

print("first struct instance property : \(firstStructInstance.property)")
print("second struct instance property : \(secondStructInstace.property)")

let firstClassReference = ReferenceType()
var secondClassReference = firstClassReference
secondClassReference.property = 2

print("first class reference property : \(firstClassReference.property)")
print("second class reference property : \(secondClassReference.property)")


//

struct SomeStruct{
    var someProperty: String = "Property"
}

var someStructInstance: SomeStruct = SomeStruct()

func someFunction(structInstance: SomeStruct){
    var localVar: SomeStruct = structInstance
    localVar.someProperty = "ABC"
}

someFunction(structInstance: someStructInstance)
print(someStructInstance.someProperty)

//
class SomeClass{
    var someProperty: String = "Property"
}

var someClassInstance: SomeClass = SomeClass()

func someFunction(classInstance: SomeClass){
    var localVar: SomeClass = classInstance
    localVar.someProperty = "ABC"
}

someFunction(classInstance: someClassInstance)
print(someClassInstance.someProperty)

0개의 댓글