双可选 (??) 和双展开 (!!) 带有 Swift 中的按钮文本
Double optionals (??) and double unwrapping (!!) with Button text in Swift
我在标准单视图项目中有一个标准 UIButton
。我想在单击按钮时获取按钮的文本。但是,在 Xcode 7.0 GM 中,编译器要求我使用 ??
、?!
或 !!
,我的行为很奇怪。当试图展开文本时,会出现更奇怪的行为:只有三重展开才能最终做到这一点。
@IBAction func buttonTapped(sender: AnyObject) {
print( sender.titleLabel?!.text ) // Optional("Button")
print( sender.titleLabel??.text ) // Optional("Button")
print( sender.titleLabel!!.text ) // Optional("Button")
print( sender.titleLabel?!.text! ) // Optional("Button")
print( sender.titleLabel??.text! ) // Optional("Button")
print( sender.titleLabel!!.text! ) // Button
}
这是怎么回事?
我看过
但是 sender
在这里不是一个数组,我看不出这些答案的联系。
这是因为AnyObject
。第一个 ?
用于 "is it an object that responds to the titleLabel
method?",第二个 ?
用于 "is the title label nil?"
如果您只是从 Interface Builder 连接一个 按钮 ,您可以使用
@IBAction func buttonTapped(sender: <b>UIButton</b>)
当您确定您的发件人始终是 UIButton
那么为什么您的输入参数是 AnyObject
。以下声明将解决您的问题:
@IBAction func buttonTapped(sender: UIButton) {
print( sender.titleLabel!.text ) // Optional("Button")
print( sender.titleLabel!.text ) // Optional("Button")
print( sender.titleLabel!.text ) // Optional("Button")
print( sender.titleLabel!.text! ) // Optional("Button")
print( sender.titleLabel!.text! ) // Optional("Button")
print( sender.titleLabel!.text! ) // Button
}
我在标准单视图项目中有一个标准 UIButton
。我想在单击按钮时获取按钮的文本。但是,在 Xcode 7.0 GM 中,编译器要求我使用 ??
、?!
或 !!
,我的行为很奇怪。当试图展开文本时,会出现更奇怪的行为:只有三重展开才能最终做到这一点。
@IBAction func buttonTapped(sender: AnyObject) {
print( sender.titleLabel?!.text ) // Optional("Button")
print( sender.titleLabel??.text ) // Optional("Button")
print( sender.titleLabel!!.text ) // Optional("Button")
print( sender.titleLabel?!.text! ) // Optional("Button")
print( sender.titleLabel??.text! ) // Optional("Button")
print( sender.titleLabel!!.text! ) // Button
}
这是怎么回事?
我看过
但是 sender
在这里不是一个数组,我看不出这些答案的联系。
这是因为AnyObject
。第一个 ?
用于 "is it an object that responds to the titleLabel
method?",第二个 ?
用于 "is the title label nil?"
如果您只是从 Interface Builder 连接一个 按钮 ,您可以使用
@IBAction func buttonTapped(sender: <b>UIButton</b>)
当您确定您的发件人始终是 UIButton
那么为什么您的输入参数是 AnyObject
。以下声明将解决您的问题:
@IBAction func buttonTapped(sender: UIButton) {
print( sender.titleLabel!.text ) // Optional("Button")
print( sender.titleLabel!.text ) // Optional("Button")
print( sender.titleLabel!.text ) // Optional("Button")
print( sender.titleLabel!.text! ) // Optional("Button")
print( sender.titleLabel!.text! ) // Optional("Button")
print( sender.titleLabel!.text! ) // Button
}