Dharmesh Kheni Dharmesh Kheni - 6 months ago 9
Swift Question

How to get label name from Button?

I am new in

Swift
and I am making a simple calculator where I wan't to detect a button which was pressed and my code is below.

@IBAction func ButtonTapped(TheButton : UIButton){

println(TheButton.titleLabel.text)
}


But It Shows me error like
"UILabel? Does not have a member a named text"


and it tell me to modify code like this

println(TheButton.titleLabel?.text)


This Prints
Optional("1")
(1 is my button name)

So anybody can help me why this is happend to me and how can I print my button name without Optional?

Answer

If you are sure that titleLabel is not nil:

println(TheButton.titleLabel!.text)

else

if let text = TheButton.titleLabel?.text {
    println(text)
}
Comments