[swift] 옵셔널 (optional) / 타입 캐스팅 (typecasting)

Snyong·2023년 9월 29일

swift

목록 보기
10/10
post-thumbnail

Optional

  • swift에서는 value가 있거나 없음을 표현할 수 있는 optional 제공
  • ?를 이용해서 표현하며, 값이 없는 경우 nil로 표현
var age: Int? = nil
print(age) // nil

age=12
print(age) // Optional(12)

💡 12가 아니라 Optional(12)가 나온다는 점을 주의하자

Unwrapping Optionals

  • Optional 타입의 값만 가져오는 방법을 unwrapping 한다고 함
  • 대표적으로 if let을 이용
if let unwrapped = age {
    print("age: \(unwrapped)") // 12
} else {
    print("age is missing")
}

Unwrapping with guard

  • 메소도 또는 함수에서 guard를 이용해서 초기에 조건을 검사할 수 있음
  • guard let을 이용하면, 메소드 초기에 옵셔널 타입에서 값이 있는 경우를 검사 가능
func printAge(age: Int?) {
    guard let unwrapped = age else {
        print("age is missing")
        return
    }
    print("age: \(unwrapped)")
}

printAge(age: age)

Force Unwrapping

  • 옵셔널 타입에 값이 있다고 '확신'하는 경우, 강제 unwrapping 할 수 있음
  • ! 키워드를 이용해 강제 unwrapping 구현
let forcedUnwrapped = age!
// Optional(12) 아니고, 12

Nil Coalescing

  • optional 타입에 값이 없는 경우, default 값을 설정하고 싶을때 이용
  • ??을 이용해서 default 값 설정
age = nil
let currentAge = age ?? 20 // 20

Optional chaining

  • 옵셔널 타입의 프로퍼티 접근시 optional chaining (?마크) 사용됨
  • 일종의 경고
struct Developer {
    var name: String
}

var jason: Developer? = Developer(name: "Jason")
print(jason?.name) // Optional("Jason")

jason = nil
print(jason?.name) // nil 

Typecasting

  • swift에서는 부모 타입에서 자식 타입으로 변형 가능한지를 확인할때 as? 키워드 사용
class Animal {
    
}

class Cat: Animal {
    
}

class Dog: Animal {
    func bark() {
        print("wal wal")
    }
}

let pets: [Animal] = [Cat(), Dog(), Cat(), Dog()]

for pet in pets {
    if let dog = pet as? Dog {
        dog.bark()
    }
}

0개의 댓글