If a variable is an Optional
what is the advantage of force unwrapping it.
class Button: UIButton {
var title: UILabel? = nil
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
func addTitle(text: String) {
title = UILabel(frame: CGRect())
self.addSubview(title!)
}
}
let a: Button = Button(frame: CGRect())
a.addTitle("Hello World")
// Case 1
a.title?.text = "Goodbye"
// Case 2
a.title!.text = "Hello World"
In Case 1 I know its safer but is there any performance improvements or reason to use Case 2?
So, if we know that Case 1 is more safe why should we ever use Case 2?
Performance-wise there might be a very to very very small no difference between forced and optional binding/chaining, as the optional version might have an extra if
somewhere.
But nonetheless when talking about performance issues, the performance bottlenecks come from other parts of the code, like non-improved loops, lots of accumulation NSNotification
's sent in a short amount of time, unnecessary redraws of the UI, etc.
So it's best to stay on the safer side and use optional binding/casting/chaining and focus on the parts of the code that adds actual performance penalties. Even if at the time you write the code the value is guaranteed to be non-nil
, in the future in might be that the conditions will change and you'll suddenly end up with crashes that you didn't expect they'll occur.
Swift has made it very easy to deal with optionals, without writing a lot of boilerplate code, you should take advantage of those features.