Good Morning everyBody,
I would like to ask why sometimes we put the Character "!" ?
and sometimes we put the Character "?" (like as?)
please explain me these.
Good Morning everyBody,
I would like to ask why sometimes we put the Character "!" ?
and sometimes we put the Character "?" (like as?)
please explain me these.
"?" is called Optional and "!" is Implicitly Unwrapped Optionals. You can find more info here in Optionals and Implicit Unwrapped Optionals Section.
Some excerpt as follow:
Optionals (?): Swift introduces optional types, which handles absence of value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all.
Implicitly Unwrapped Optionals (!): Sometimes it is clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional’s value every time it is accessed, because it can be safely assumed to have a value all of the time.
As swift compiler is more strict in object use, you have to be put the optional object or non-optional object in your call. However, XCode has auto-complete feature for code editing so that the compiler validate your code.
Generally, XCode add ! to your variable when you pass an optional variable to a call that requires a non-optional variable. This case is dangerous cause if your object does not have value, application can be crashes. You should verify your self or you have to sure that your object contains value.
And, XCode add ? to your variable to give your optional variable a chance to unwrap and to be used if possible. Of course, the API in your call must accept an optional variable. Also, this is to try to cast your variable to the right format. Take a look at "Optional Chaining" document in Apple site here.
To put it as simply as i can:
? means it`s optional. So the variable could be nil or its actual value
! means that this value should never be nil. And if for any reason this became nil the app should crash.
My advice is to never use "!" because you don`t want you are app to crash. Instead if you have an optional use the unwrapping method bellow:
var x:String? = nil
if let unwrapped_x = x {
//x is not nil
}
else{
//x is nil
}