Swift "unwrapped value"

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

Swift "unwrapped value"

文章rusli » 週四 4月 14, 2016 10:53 am

代碼: 選擇全部

        var canBeNil1 : Int? = 4
        print("canBeNil1 : \(canBeNil1!)")  // unwrap it. return 4
        canBeNil1 = nil
        print("canBeNil1 : \(canBeNil1)")  // return nil
        // print("canBeNil1 : \(canBeNil1!)") // fatal error: unexpectedly found nil while unwrapping an Optional value
       
        // automatically unwrap
        let canBeNil2: Int! = 4
        print("canBeNil2 : \(canBeNil2!)") // return 4
       
        let canBeNil3: Int! = nil
        print("canBeNil3 : \(canBeNil3?.toIntMax())") // return nil, ignore toIntMax()
        // print("canBeNil3 : \(canBeNil3!.toIntMax())") // fatal error: unexpectedly found nil while unwrapping an Optional value
       
        // let maxInt = canBeNil3.toIntMax() // fatal error: unexpectedly found nil while unwrapping an Optional value
        // print("maxInt : \(maxInt)")
        if let maxInt = canBeNil3?.toIntMax() // if canBeNil3 is null then run else
        {
            print("maxInt : \(maxInt)")
        }
        else
        {
             print("maxInt : 0")
        }
       
        let stringBeNil1: String? = "abc"
        print("stringBeNil1 : \(stringBeNil1)") // return Optional("abc")
        if let newString = stringBeNil1
        {
            print("newString : \(newString)") // return abc
        }
       
        var stringBeNil2: String! = "abc"
        print("stringBeNil2 : \(stringBeNil2)") // return abc
        stringBeNil2 = nil
        print("stringBeNil2 : \(stringBeNil2)") // return nil

回到「Swift」

誰在線上

正在瀏覽這個版面的使用者:沒有註冊會員 和 1 位訪客