为什么我必须使用 print((sender as AnyObject).currentTitle!!) 来打印标题和 print(sender.currentTitle) 不起作用?

why i have to use print((sender as AnyObject).currentTitle!!) to print title and print(sender.currentTitle) not work?

提问人:Zaher Mohamed Masloub 提问时间:1/6/2020 最后编辑:Ricardo GonzalezZaher Mohamed Masloub 更新时间:1/7/2020 访问量:160

问:

为什么当我尝试打印我使用的按钮标题并且不起作用时。print(sender.currentTitel)

下面就是工作:

print((sender as AnyObject).currentTitle!!)

iOS的 swift iphone swift3 swift2

评论

0赞 KSigWyatt 1/7/2020
欢迎来到 SO!您必须强制转换对象才能打印它的原因是 Optionals。在“解包”可选选项时,您通常需要提供默认值,或者告诉程序它应该将对象“解包”为什么。如果未提供此默认值,则必须告诉应用程序使用 “bang” 运算符强制强制转换。您可以在开发人员文档中了解有关它们的更多信息。例如,在编写带有条件参数的函数时,它们可能很有用。developer.apple.com/documentation/swift/optional!

答:

1赞 jlngdt 1/6/2020 #1

我假设您处于这样的函数中:IBAction

    @IBAction func buttonTapped(_ sender: Any) {
        // print here
    } 

这是由于您在创建 IBAction 时声明的引用。二是解决方案。Any

您可以像这样修改您的 IBAction:

    @IBAction func buttonTapped(_ sender: UIButton) {
        // print(sender.titleLabel?.text)
    } 

或测试发件人一致性:

    @IBAction func buttonTapped(_ sender: Any) {
        if let button = sender as? UIButton {
            // print(button.titleLabel?.text)
        }
    } 
  • 如果 IBAction 仅由按钮触发,则解决方案 1 会更好
  • 如果您的 IBAction 由多个发件人使用,则解决方案 2 可能是一种方法

干杯