출처: https://developer.apple.com/documentation/swift/optional
Apple Developer Documentation
developer.apple.com
enum을 정해진 case 대로 쓸 때도 있지만 그 때 그 때 변하는 case를 가지는 enum도 있다. '관련값(associated)을 가지는 enum'이라고들 부르는 것 같다. 사실 Optional도 '관련 값을 가지는 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)")
}
반응형
'swift & iOS > swift' 카테고리의 다른 글
[swift] error handling - throws 메소드 & do ... catch 문 (0) | 2022.01.28 |
---|---|
[swift] 옵셔널 체이닝 optional chaining (0) | 2022.01.28 |
[swift] 함수의 inout 파라미터 (0) | 2022.01.27 |
[swift] 함수에서 여러 개의 값을 반환하기 (튜플) (0) | 2022.01.27 |
[swift] 문자열 끝에서 자르기 dropLast() (0) | 2022.01.23 |