Programming/Swift

[스크랩] 스위프트 옵셔널 이해하기

평생초보 2016. 9. 7. 22:03
반응형

http://chanlee.github.io/2015/06/14/Introduce-Swift-Optional/

https://www.appcoda.com/beginners-guide-optionals-swift/

https://devxoul.gitbooks.io/ios-with-swift-in-40-hours/content/Chapter-2/optionals.html


playground에서 예제를 똑같이 실행해 보았다.

import UIKit


class Messenger {

    var message1: String = "Swift is awesome"

    var message2: String?

}


func findStockCode(company: String) -> String? {

    if (company == "Apple") {

        return "AAPL"

    } else if (company == "Google") {

        return "GOOG"

    }

    

    return nil

}


var stockCode:String? = findStockCode("Facebook")

let text = "Stock Code - "

//let message = text + stockCode!

//print(message)



if let tmpStock = stockCode {

    let message = text + tmpStock

    print(message)

}


if var stockCode = findStockCode("Facebook") {

    let message = text + stockCode

    print(message)

}



class Stock {

    var code: String?

    var price: Double?

}


func findStockCode2(company: String) -> Stock? {

    if (company == "Apple") {

        let aapl: Stock = Stock()

        aapl.code = "AAPL"

        aapl.price = 90.32

        

        return aapl

    } else if (company == "Google") {

        let goog: Stock = Stock()

        goog.code = "GOOG"

        goog.price = 556.36

        

        return goog

    }

    return nil

}


if let stock = findStockCode2("Apple") {

    if let sharePrice = stock.price {

        let totalCost = sharePrice * 100

        print(totalCost)

    }

}


if let sharePrice = findStockCode2("Apple")?.price {

    let totalCost = sharePrice * 100

    print(totalCost)

}


반응형