아미(아름다운미소)

[문법요약] 옵셔널 체이닝(Optional Chaining) 본문

랭귀지/SWIFT

[문법요약] 옵셔널 체이닝(Optional Chaining)

유키공 2017. 12. 14. 17:59

-옵셔널 체이닝(Optional Chaining)

//: Playground - noun: a place where people can play
import UIKit

var str = "손흥민"
//str = nil // Error
var name: String? = "손흥민"
var name2: Optional<String> = "흥민"
print(name ?? "nil 이라서 기본값 출력함")
print(name!)

var name3: String! = "손흥민"
var name4: ImplicitlyUnwrappedOptional<String> = "손흥민"
print(name3)

if name != nil {
    print(name!)
} else {
    print("nil 입니다")
}

// 옵셔널 바인딩
if let n = name {
    print("#########" + n)
} else {
    print("nil 입니다")
}

let dic = ["KR": "서울", "US": "워싱턴"]
print(dic["K"] ?? "기본값")

if let v = dic["KR"] {
    print(v + " 강남구 역삼동")
} else {
    print("nil 입니다")
}

let weight = "67"
if let iWeight = Int(weight) {
    print(iWeight)
}

//guard let w = Int(weight) else {
//    print("nil 입니다")
//    return
//}
//
//print(w)

// 옵셔널 체이닝(Optional Chaining)
class Birthday {
    var year: Int = 0
    var month: Int?
	init(year: Int, month: Int) {
        self.year = year
        self.month = month
    }
}


class UserInfo {
    var birthday: Birthday?
    init() {
        birthday = Birthday(year: 1980, month: 4)
    }
}

class CompanyInfo {
    var userInfo: UserInfo?
    init() {
        userInfo = UserInfo()
    }
}

var companyInfo: CompanyInfo? = CompanyInfo()

if let cInfo = companyInfo {
    if let uInfo = cInfo.userInfo {
        if let birth = uInfo.birthday {
            if let mon = birth.month {
                print(mon)
            }
        }
    }
}
print(companyInfo?.userInfo?.birthday?.month)


'랭귀지 > SWIFT' 카테고리의 다른 글

날짜와 시간 다루기 (Swift)  (0) 2018.01.03
XCode 단축키 정리  (0) 2017.12.27
[문법요약] Structure  (0) 2017.12.14
[문법요약] 열거형(Enumeration)  (0) 2017.12.14
[문법요약] 함수  (0) 2017.12.13
Comments