0

Screenshot of simulator screen

Hello all. I just recently started trying to learn coding in Swift 2. I am trying to make a very simple app where I can add scores, push my "calculate" button and display the total in a label. I was able to do that as seen in the screenshot. The problem I have is if I don't put a score in one of the textfields and still try to calculate it, it crashes. This is my code:

    class ViewController: UIViewController {


@IBOutlet weak var score1: UITextField!

@IBOutlet weak var score2: UITextField!

@IBOutlet weak var score3: UITextField!

@IBOutlet weak var total: UILabel!

@IBAction func Calculate(sender: AnyObject) {

    let score1 = Int(score1.text!)!
    let score2 = Int(score2.text!)!
    let score3 = Int(score3.text!)!
    let alltogether = (scoreone) + (scoretwo) + (scorethree)

    total.text = "Your total score is \(alltogether)!"

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

Could someone point me in the direction I need to look. I am thinking I need to add some sort of exemption if the field is nil. Or something along the lines of making the default int 0??? Thank you all!

CincyWong
  • 3
  • 1
  • You're forcibly unwrapping an optional variable. If any field, say text field `score1`, is empty, the the following line of code, `let score1 = Int(score1.text!)!`, will fail as the `Int` initializer will return `nil` when send an empty string. There exists several threads here on SO explaining how to safely unwrap optionals, as well as how to convert `String` values to `Int`, see e.g. [LeoDabus answer in this thread](http://stackoverflow.com/a/34294660/4573247). – dfrib Jan 13 '16 at 01:11
  • Possible duplicate of [Swift - Converting String to Int](http://stackoverflow.com/questions/24115141/swift-converting-string-to-int) – dfrib Jan 13 '16 at 01:20

1 Answers1

2
let score1 : Int = Int(score1.text ?? "") ?? 0
let score2 : Int = Int(score2.text ?? "") ?? 0
let score3 : Int = Int(score3.text ?? "") ?? 0

This will yield value 0 in case your fields are empty or otherwise non-numerical (or if UITextField property .text contains nil).

dfrib
  • 70,367
  • 12
  • 127
  • 192
  • Thanks so much! Worked perfect. That answer helped me figure out how to work in Double as well. – CincyWong Jan 13 '16 at 02:30
  • @ChrisWong Happy to help! Have a look at the linked thread http://stackoverflow.com/questions/24115141/swift-converting-string-to-int as well, lots of valuable information there in this context. – dfrib Jan 13 '16 at 02:31