- μ΅μ λ μΆμΆμ΄λ?
- μ΅μ λμ λ€μ΄μλ κ°μ μ¬μ©νκΈ° μν΄ κΊΌλ΄μ€λ κ²
- μ΅μ λ λ°©μ
- μ΅μ λ λ°μΈλ©
1. nil μ²΄ν¬ + μμ ν μΆμΆ
2. μ΅μ
λ μμ κ°μ΄ λ€μ΄μλμ§ νμΈνκ³ κ°μ΄ μμΌλ©΄ κ°μ κΊΌλ΄μ¨λ€.
3. if-let λ°©μ μ¬μ©
func printName(_ name: String) {
print(name)
}
var myName: String? = nil
//printName(myName)
// μ λ¬λλ κ°μ νμ
μ΄ λ€λ₯΄κΈ° λλ¬Έμ μ»΄νμΌ μ€λ₯λ°μ
if let name: String = myName {
printName(name)
} else {
print("myName == nil")
}
var yourName: String! = nil
if let name: String = yourName {
printName(name)
} else {
print("yourName == nil")
}
// name μμλ if-let ꡬ문 λ΄μμλ§ μ¬μ©κ°λ₯νλ€
// μμ μ¬μ©λ²μλ₯Ό λ²μ΄λ¬κΈ° λλ¬Έμ μ»΄νμΌ μ€λ₯ λ°μ
//printName(name)
// ,λ₯Ό μ¬μ©ν΄ ν λ²μ μ¬λ¬ μ΅μ
λμ λ°μΈλ© ν μ μλ€
// λͺ¨λ μ΅μ
λμ κ°μ΄ μμ λλ§ λμνλ€
myName = "kdgt"
yourName = nil
if let name = myName, let friend = yourName {
print("\(name) and \(friend)")
}
// yourNameμ΄ nilμ΄κΈ° λλ¬Έμ μ€νλμ§ μλλ€
yourName = "hana"
if let name = myName, let friend = yourName {
print("\(name) and \(friend)")
}
// kdgt and hana
- κ°μ μΆμΆ : μ΅μ λμ κ°μ΄ λ€μ΄μλμ§ μλμ§ νμΈνμ§ μκ³ κ°μ λ‘ κ°μ κΊΌλ΄λ λ°©μ, λ§μ½ κ°μ΄ μμ κ²½μ°(nil) λ°νμ μ€λ₯κ° λ°μνκΈ° λλ¬Έμ μΆμ²X
var myName: String? = kdgt
var youName: String! = nil
printName(myName!) // kdgt
myName = nil
//print(myName!)
// κ°μ μΆμΆμ κ°μ΄ μμΌλ―λ‘ λ°νμ μ€λ₯ λ°μ
yourName = nil
//printName(yourName)
// nil κ°μ΄ μ λ¬λκΈ° λλ¬Έμ λ°νμ μ€λ₯λ°μ