1 頁 (共 1 頁)

Swift "unwrapped value"

發表於 : 週四 4月 14, 2016 10:53 am
rusli

代碼: 選擇全部

        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