sebiraw
sebiraw

Reputation: 15

Cannot convert value of type 'String?' to type 'NSString' in coercion

Im trying to make this calculator for various math formulas and I'm stuck at this point. I was following this tutorial

Here's my code:

import UIKit

class pythagorasViewController: UIViewController {


@IBOutlet weak var aLabel: UILabel!
@IBOutlet weak var bLabel: UILabel!
@IBOutlet weak var aField: UITextField!
@IBOutlet weak var bField: UITextField!
@IBOutlet weak var answerLabel: UILabel!
@IBAction func calculateButton(_ sender: UIButton) {
    var a = (aField.text as NSString).floatValue
    var b = (bField.text as NSString).floatValue
    var answer = sqrt(a*a + b*b)
    answerLabel.text = "\(answer)"
}

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

The part where I'm getting the error is at:

var a = (aField.text as NSString).floatValue
var b = (bField.text as NSString).floatValue

Upvotes: 1

Views: 7818

Answers (1)

Josh Homann
Josh Homann

Reputation: 16327

Prefer let to var when possible. You do not need to use NSString. You can cast String to Float?. You need to unwrap both the text property which is a String? (if you have a question about the type of a variable option click and it will show you) and the Float? conversion:

func calculateButton(_ sender: UIButton) {
    guard let aText = aField.text,
          let bText = bField.text,
          let a = Float(aText),
          let b = Float(bText) else {
        return
    }
    let answer = sqrt(a*a + b*b)
    answerLabel.text = "\(answer)"
}

Upvotes: 1

Related Questions