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

174 Views Asked by At

Why when I try to print button title i used print(sender.currentTitel) and isn't working.

And this in below it is work:

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

1

There are 1 best solutions below

0
jlngdt On

I assume you are in a IBAction function like this:

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

This is due to the Any reference you declare when you create the IBAction. Two solution.

You can modify your IBAction like this:

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

or test the sender conformance:

    @IBAction func buttonTapped(_ sender: Any) {
        if let button = sender as? UIButton {
            // print(button.titleLabel?.text)
        }
    } 
  • Solution 1 is better if your IBAction is only triggered by button(s)
  • Solution 2 may be an approach if your IBAction is used by multiple senders

Cheers