Swift可選類型和可選鏈

來源:互聯網
上載者:User

標籤:swift可選類型和可選鏈

一、可選類型


    有時候在Swift程式的運算式可以看到?和!等符號,它們代表的含義是什麼,這些符號都和可選類型有關。

    有時候使用一個變數和常量,它儲存的值可能有也可能沒有


    1、比較給一個變數賦值nil,需要下面的運算式賦值


    class Empoyee{

        var  int : = 0

        var name:String = ""

        var job : String =""

}


    var emp : Employee? = nil //後面加上?號可以接受空值,不加?不能賦予空值

    emp1=Employee()

    println(emp!.no)


    2、引用代碼


        emp1?.no=1000

        emp1?.name="張三"

        emp1?.job="clerk"


    3、再看樣本

        func divided(n1:Int,n2:Int)->Double?{

            if n2==0{

            return nil

}

        Double(n1)/Double(n2)

}

    let result : Double? = divide(100,200)

本文出自 “平凡之路” 部落格,請務必保留此出處http://linjohn.blog.51cto.com/1026193/1621250

Swift可選類型和可選鏈

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.