简体   繁体   中英

Difference between optional values in swift?

What is the difference between:

var title:String? = "Title" //1
var title:String! = "Title" //2
var title:String = "Title" //3

What am I saying if I were to set title in each way and am I forced to unwrap each variable in a different way?

Think about ? and ! like a box that might have a value or not. 在此输入图像描述

I recommend this article .

  1. Optional box that might have value or might not , and that optional box is not unwrapped.

     var title:String? = "Title" //second and third picture 

    You use unwrapped value like that:

     if let title = title { //do sth with title, here is the same like let title: String = "Title" } 
  2. Optional box that might have a value or might not , and that optional box is actually unwrapped. If there is a value and you access that value, that is ok ( second image , just replace ? with ! ), but if there is no value, then app crash ( third image , just replace ? with ! )

     var title:String! = "Title" 
  3. That variable have a value for sure , and you cannot assign to this value nil (because it is not optional). Optional means that there is a value or there is no value ( nil ):

     var title:String = "Title" //first picture 

`var title:String? = "Title"`

title currently has a value of Title , but in the future it could possibly be nil . I will need to unwrap it using optional binding:

if let unwrappedTitle = title {
   println(unwrappedTitle)
}

Or by forcing the unwrap with the ! character

let unwrappedTitle = title!

The above will crash if title is nil

`var title:String! = "Title"`

title currently has a value of "Title" . It could possibly be nil, but I know that it never will be when I am using it. You don't need to unwrap this with optional binding or by forcing the unwrap with the ! character.

Your program will crash if this value is ever accessed while nil , but the compiler will let you set this value to nil .

`var title:String = "Title"`

title currently has a value of "Title" . This may change, but the variable title will always have some string value. I don't need to check for nil with optional binding or by forcing an unwrap. The compiler will not let you build if you try to set title to nil .

var title:String? = "Title" //1 Nil Possible-Force Unwrap needed-Nil checking when use
var title1:String! = "Title"//2 Nil Possible-Force Unwrap not needed-Nil cheking when Use
var title2:String = "Title" //3 Nil Not possible as its initailize when declared-No force unwrap needed-No Nil Cheking is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM