iOS 응용 (swift)
[iOS - swift] for문에서 Optional 간결하게 unwrap하는방법 (for문 unwrap)
jake-kim
2024. 1. 13. 22:38
Optional 타입
- Optional 타입은 제네릭스를 받고, 그 제네릭스는 Optional 안에 감싼 값을 의미
- Optional 타입은 enum이며, 2개의 case가 존재
- none: 값이 없는 case
- some(Wrapped): 값이 있는 case
enum Optional<Wrapped>: ExpressibleByNilLiteral {
case none
case some(Wrapped)
}
- 조건문에서 unwrap 방법
- .some으로 접근
- 변수?로 접근
let optionalString = Optional<String>("jake")
switch optionalString {
case .none:
print("this is nil")
case let .some(value):
print("some value = ", value)
}
switch optionalString {
case .none:
print("this is nil")
case let unwrappedValue?:
print("unwrappedValue = \(unwrappedValue)")
}
for문에서 unwrap 방법
- 보통 for-in안에서 if문을 아래처럼 사용
let arr: [Optional] = [Optional(1),2,3,4]
for val in arr {
if let val {
print(val)
}
}
- for문 + case를 사용하면 간결하게 표현이 가능
for case let val? in arr {
print(val)
}
(혹은 .some으로도 가능)
for case let .some(val) in arr {
print(val)
}