Optional(μ΅μ λ): κ°μ΄ μμ μλ μκ³ μμ μλ μλ κ²
let optionalConstant: Int? = nil // possible
let someConstant: Int = nil // error
enum Optional<Wrapped> : ExpressibleByNilLiteral {
case none //κ°μ΄ μλ κ²
case some(Wrapped) //κ°μ΄ μλ κ² λ λ€ νν κ°λ₯
}
// λ λ€ μ¬μ© κ°λ₯
let optionalValue: Optional<Int> = nil
let optionalValue: Int? = nil
-
λͺ μμ νν
- nilμ κ°λ₯μ±μ μ½λλ§μΌλ‘ νν κ°λ₯
- λ¬Έμ/μ£Όμ μμ± μκ° μ μ½
-
μμ ν μ¬μ©
- μ λ¬λ°μ κ°μ΄ μ΅μ λμ΄ μλλΌλ©΄ nil 체ν¬λ₯Ό νμ§ μκ³ μ¬μ© κ°λ₯
- μμΈ μν©μ μ΅μν νλ μμ νκ³ ν¨μ¨μ μΈ μ½λ©
-
!
(Implicitly Unwrapped Optional)- μμμ μΆμΆ μ΅μ λ
- κΈ°μ‘΄ λ³μμ²λΌ μ¬μ© κ°λ₯
-
?
(General Optional)- κΈ°μ‘΄ λ³μμ²λΌ μ¬μ© λΆκ° - μ΅μ λκ³Ό μΌλ° κ°μ λ€λ₯Έ νμ μ΄λ―λ‘ μ°μ° λΆκ°
- if-let
- nil μ²΄ν¬ & μμ ν κ° μΆμΆ
var myName: String? = "wonseok" var yourName: String? = nil if let name = myName, let friend = yourName { print("\(name) and \(friend)") } // yourNameμ΄ nilμ΄κΈ° λλ¬Έμ μ€νλμ§ μλλ€ yourName = "sujeong" if let name = myName, let friend = yourName { print("\(name) and \(friend)") } // wonseok and sujeong
- Force Unwrapping(κ°μ μΆμΆ)
- nil μ²΄ν¬ μμ΄ κ°μ λ‘ κ°μ κΊΌλ΄λ λ°©μ, κ°μ΄ μμ κ²½μ° λ°νμ μ€λ₯κ° λ°μνμ¬ μ±μ΄ λ©μΆκΈ° λλ¬Έμ μΆμ²λμ§ μλ λ°©μ
var myName: String? = nil print(myName!) // error κ°μ΄ μμ΄μ λ°νμ μ€λ₯
-
μ΅μ λ 체μ΄λ
// μ¬λ ν΄λμ€ class Person { var name: String var job: String? var home: Apartment? init(name: String) { self.name = name } } // μ¬λμ΄ μ¬λ μ§ ν΄λμ€ class Apartment { var buildingNumber: String var roomNumber: String var `guard`: Person? var owner: Person? init(dong: String, ho: String) { buildingNumber = dong roomNumber = ho } } let wonseok: Person? = Person(name: "wonseok") let apart: Apartment? = Apartment(dong: "101", ho: "202")
μ΄λ° μ½λκ° μμ λ Person Aμ Apartmentμ κ²½λΉμ μ§μ μ΄ κΆκΈνλ€λ©΄?
// μ΅μ λ 체μ΄λμ μ¬μ©νμ§ μλλ€λ©΄ μ΄λ κ² λ¨ func guardJob(owner: Person?) { if let owner = owner { // 1.μ¬λμ μ‘΄μ¬ μ¬λΆ if let home = owner.home { // 2.κ·Έ μ¬λμ μ§ μ¬λΆ if let 'guard' = home.guard { // 3.κ·Έ μ¬λμ μ§μ κ²½λΉμ μ¬λΆ if let guardJob = 'guard'.job { // 4.κ·Έ μ¬λμ μ§μ κ²½λΉμμ μ§μ μ¬λΆ print("μ°λ¦¬μ§ κ²½λΉμμ μ§μ μ \(guardJob)μ λλ€") } else { print("μ°λ¦¬μ§ κ²½λΉμμ μ§μ μ΄ μμ΄μ") } } } } }
// μ΅μ λ 체μ΄λμ μ¬μ©νλ€λ©΄ func guardJobwithOptionalChaining(owner: Person?) { if let guardJob = owner?.home?.guard?.job { print("μ°λ¦¬μ§ κ²½λΉμμ μ§μ μ \(guardJob)μ λλ€") } else { print("μ°λ¦¬μ§ κ²½λΉμμ μ§μ μ΄ μμ΄μ") } } guardJobwithOptionalChaining(owner: wonseok) // μ°λ¦¬μ§ κ²½λΉμμ μ§μ μ΄ μμ΄μ
-
nil λ³ν© μ°μ°μ
- OptionalΒ
??
Β Value - μ΅μ λ κ°μ΄Β nilμΌ κ²½μ°, μ°μΈ‘μ κ°μ λ°νν©λλ€.
var house: String house = wonseok?.home?.owner?.name ?? "λ³ΈμΈ" // -> '??' μμ κ°μ΄ nilμ΄λΌλ©΄ "λ³ΈμΈ"μ ν λΉν΄λ¬λΌ! print(house) // λ³ΈμΈ // μμμ 'λ³ΈμΈ'μ λ£μ΄μ€μ nilμ΄ μλ
- OptionalΒ