SWIFT Optional Value

來源:互聯網
上載者:User

標籤:

 SWIFT中有一個類型定義叫可選值,在變數類型後面加一個?號即可定義一個類型為Optional Value的變數,當在使用變數時要用到強制解包!.

 如在頁面上有一個可選輸入年齡的框,在接受資料的時間就可能要定義一個可選值的變數. 

 var age:Int? = 10

 var str:String = "Age is "+String(age!)

 以下為從一個數組中取資料,然後判斷是否存在值 

  var numberOfLegs = ["ant":6, "snake":0, "dog":4]

  var possibleLegCount:Int? = numberOfLegs["fish"] //沒有找到相應的索引值將會返回nil

  判斷possibleLegCount是否是nil

  if possibleLegCount == nil{

    println("not found")

  }else{

    var legCount = possibleLegCount! //強制解包

    println("fish‘s legs is \(legCount)")

    println("fish‘s legs is \(possibleLegCount)")  //用這種佔位方式會自動解包

}

 

  此時的possibleLegCount一定要是Optional Value類型,否則會報錯.此時程式將會驗證可選值是否可以正常解包,正常的話將會把值解包後賦值給legCount變數 

  if let legCount = possibleLegCount { 

    println("fish‘s legs is \(legCount)")

}

 

SWIFT Optional Value

相關文章

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.