+ 1
Plz any ios developer explain how optionals can work?
what is the use of ? and ! symbols, when and where and at what conditions ,shall i use those? read some net materials but no profit?any nice guy here?
6 ответов
+ 3
? means that a variable may or may not have a value so if you are not sure that a variable may not have a value then you declare it with?
else use!
+ 1
ok, optional is a key concept in swift and I too have limited understanding of it. here goes
you use an optimal when you are not sure if the variable will have value. In case there is a chance that there can be no value(or a nil value) ALWAYS use optional.
to declare a optional, you use a ? at the end of the type. this denotes that the variable is an optional and may have no value(nil). for eg, var favouriteMovie = String?
+ 1
part 2
this means a parameter which is an optional string. it is an optional and its associated value is a string type.
that was declaring an optional. now when you want to fetch the value of an optional parameter, you need to unwrap it. that is what ! does. remember if you unwrap an optional which is nil, your program will crash(which is good actually becuase you don't want your app to give wrong output, crash is better than incorrect output. it will crash becuase you are trying to extract a value when there is none. )
+ 1
part 3
to prevent crashing use
if let
so for eg, to unwrap the above example, you will do
if let favMovie = favouriteMovie! {
whatever you want to execute if a favourite movie exists.
}
in this case, program will not crash. if there is no favouriteMovie(that is, it is nil), this block of code will not execute.
+ 1
final part!
however if you simply did
let newFav = favouriteMovie!
your program will crash if value of favouriteMovie is not set(nil)
this part below is slightly more info and you may ignore this:
optional values do not need an initial value, they are always initialised as nil.
then there is implicit unwrapping of optionals. in that while declaring an optional itself you use !
what this does is, declare that variable as optional and when calling you don't have to unwrap using !, you can simply call the parameter and it will be unwrapped(because you unwrapped it while declaring itself. ) of course in case of a nil value it will crash again.
so there, both ? and ! denote optional value and you use them to declare optional value depending upon the case
sorry for long answer I wrote and realised can't write such long one in one post!
hope this helped a bit
+ 1
when you know a certain variable has a value and cant be nil you use ! and if you are uncertain and the variable may contain nil at some point in the program execution you use ?