轉Swift之?和!

來源:互聯網
上載者:User


Swift語言使用var定義變數,但和別的語言不同,Swift裡不會自動給變數賦初始值,也就是說變數不會有預設值,所以要求使用變數之前必須要對其初始化。如果在使用變數之前不進行初始化就會報錯:
?
1 2 3 4 5 var stringValue : String   //error: variable 'stringValue' used before being initialized //let hashValue = stringValue.hashValue //                            ^ let hashValue = stringValue.hashValue

上面瞭解到的是普通值,接下來Optional值要上場了。Optional其實是個enum,裡面有None和Some兩種類型。其實所謂的nil就是Optional.None, 非nil就是Optional.Some, 然後會通過Some(T)封裝(wrap)原始值,這也是為什麼在使用Optional的時候要拆包(從enum裡取出來原始值)的原因, 也是PlayGround會把Optional值顯示為類似{Some "hello world"}的原因,這裡是enum Optional的定義:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 enum Optional<T> : LogicValue, Reflectable {      case None      case Some(T)      init()      init(_ some: T)         /// Allow use in a Boolean context.      func getLogicValue() -> Bool         /// H
相關文章

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.