问题
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?
回答1:
Think about ? and ! like a box that might have a value or not.
I recommend this article.
Optional box that might have value or might not, and that optional box is not unwrapped.
var title:String? = "Title" //second and third pictureYou use unwrapped value like that:
if let title = title { //do sth with title, here is the same like let title: String = "Title" }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"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
回答2:
`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.
回答3:
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.
来源:https://stackoverflow.com/questions/29054096/difference-between-optional-values-in-swift