swift & iOS/swift

[swift] 열거형 (enum with associated value)과 옵셔널 optional

whale3 2022. 1. 27. 17:09

출처: https://developer.apple.com/documentation/swift/optional

 

Apple Developer Documentation

 

developer.apple.com

 

enum을 정해진 case 대로 쓸 때도 있지만 그 때 그 때 변하는 case를 가지는 enum도 있다. '관련값(associated)을 가지는 enum'이라고들 부르는 것 같다. 사실 Optional도 '관련 값을 가지는 enum'이다. 

옵셔널은 제네릭 enum.

그래서 Optional 이라는 enum의 definition을 보면 아래처럼 associated value 를 가지는 enum이라는 것을 알 수 있다. case 밑에 init이랑 다른 메소드들도 있다.

@frozen public enum Optional<Wrapped> : ExpressibleByNilLiteral {

    /// The absence of a value.
    ///
    /// In code, the absence of a value is typically written using the `nil`
    /// literal rather than the explicit `.none` enumeration case.
    case none

    /// The presence of a value, stored as `Wrapped`.
    case some(Wrapped)
    
    // ....
    
}

 

그래서 옵셔널은 아래와 같이 방법으로 작성할 수 있다. 

// 출처: https://developer.apple.com/documentation/swift/optional

var x: Int? = 20
print(type(of: x)) // Optional<Int>

var y: Int? = Optional.some(20)
print(type(of: y)) // Optional<Int>

Optional.some 처럼 매번 case의 값이 달라지는 enum을 '관련값을 가지는 enum'이라고 한다. 

 

nil도 마찬가지

// 출처: https://developer.apple.com/documentation/swift/optional
let noNumber: Int? = Optional.none
print(noNumber == nil) // true

 

 

옵셔널이 associated value를 가지는 enum이라는 것과 switch 문을 활용하면 아래처럼 작성할 수도 있다. 

// 참고: https://youtu.be/UWPeBbGBs34?list=PLJqaIeuL7nuEEROQDRcy4XxC9gU6SYYXb&t=256

var name: String? = "Apple"

switch name {
    case .none:
        print("no name")
    case .some(let a):
        print("its name is \(a)")
}

 

반응형