반응형

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)

}


반응형

'Programming > Swift' 카테고리의 다른 글

Xcode8에서 발생되는 메세지  (0) 2016.09.23
Guard 활용  (0) 2016.09.13
아이폰7(?) 발표 5시간전 apple developer 등록이 안된다  (0) 2016.09.07
xcode 자동 줄바꿈 설정  (0) 2016.09.07
status bar 색상 변경  (0) 2016.09.05

+ Recent posts