0

I've got this code :

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var myLabel: UILabel!


@IBAction func myFirstButtonPressed(_ sender: UIButton) {
    let getButtonText : String = sender.title(for: .normal)!

    myLabel.text = "Clicked \(String(describing: getButtonText))"
}


@IBAction func mySecondButtonPressed(_ sender: UIButton) {
    let getSecondTitle :String = sender.title(for: .normal)!

    myLabel.text = "Clicked \(String (describing: getSecondTitle))"
}}

As you can see I've created two buttons and a label and I've used the exact same instructions on them, But when I ran the simulator on Xcode, I tried clicking the second button and the label changed perfectly without any problems.

But I when I clicked the First Button, the error occurs. It is the exact same code but why is the first button giving me an error and the second button isn't?

I'm just starting to learn IOS, and the error came after the Thread : SIGBRT when I "continue program execution".

I've seen many other people posting this problem here on stack overflow but I couldn't find a solution to the problem.

Hope you guys can help me.

WiL BaJaMas
  • 55
  • 1
  • 9

2 Answers2

0

You should not force unwrap the value coming from sender.title. Instead you should do something like:

if let text = sender.title() { 
  print(text)
}

That may cause the text not to show up (because something else may be wrong in your setup), but at least it will prevent the hard crash.

Alper
  • 3,424
  • 4
  • 39
  • 45
0

Might be this line of code return the nil value.

let getButtonText : String = sender.title(for: .normal)!

So change force wrapping to optional

let getButtonText : String? = sender.title(for: .normal)?

Also check the reference and Action of button connection.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Kishan G
  • 1
  • 1