如果一个变量是
Optional
类型,强制解包它有什么优点?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"
问题
在情况1中,我知道它更安全,但是否有任何性能改进或使用情况2的原因?
因此,如果我们知道情况1更安全,为什么还要使用情况2?
?
在可选链或可选下标中使用,因此应该跟随方法调用、属性查找或下标。 - Sebastian Osiński