powing
(Albert)
1
I noticed in official Apple code that often the bang operator is used to initialise a variable and wondered if it was safe as I was always taught not to:
var newVariable: UIColor!
cmonsour
(Christopher Monsour)
2
It’s not really a question of ‘safe’ or ‘unsafe.’ When you have an optional variable, there is inherently a question of what should happen if the variable has no value by the time it’s used. Force-unwrapping is usually a way of saying: based on the way I’ve written the program, that should never happen; if it does happen it means I’ve made a serious programming error; and there is no reasonable way for the program to proceed; thus, crash the process. Then you thoroughly test your program to make sure that never happens!
The ! is called the force-unwrap operator. However in example you provided, the ! is not being used as an operator. UIColor! indicates that the type of the variable is an implicitly-unwrapped optional. ! does not initialize a variable.
1 Like
powing
(Albert)
4
Apple may be that good, but I'm not so sure.
Bang is still bang in my book.