benpete420
benpete420

Reputation: 43

Xcode 7 beta 2 and swift not getting along

I have an error when I typed in some code, it gave me an error. It looks perfect, but here is the code:

import UIKit

class SecondViewController: UIViewController {
    @IBOutlet weak var resultLabel: UILabel!
    @IBOutlet weak var tempText1: UITextField!

    @IBAction func convertTemp1(sender: AnyObject) {
       #let fahrenheit = (tempText1.text as NSString).doubleValue
        let celsius = (fahrenheit - 32 )/1.8
        let resultText = "Celsius \(celsius)"
        resultLabel.text = resultText
    }

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

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

It give me the following error: 'String?' is not convertable to 'NSString' On the line I put a # on. The # is not in the real code.

Note: I do not understand much computer talk so please try to speak very simply. :)

Upvotes: 0

Views: 238

Answers (1)

anon
anon

Reputation:

The text property of UITextField returns an optional string but your code doesn't handle optionals. Casting to NSString isn't allowed there (also not necessary to get to the doubleValue).

You need to handle the optional. For this you could force-unwrap it using !. But that can lead to crashes. It would be better to use the if let or guard let statements:

guard let fahrenheit = tempText1.text?.doubleValue else { return }

For conciseness we use optional chaining (the ?here). We could also keep this in two steps:

guard let fahrenheitString = tempText1.text else { return }
let fahrenheit = fahrenheitString.doubleValue

Both are basically equivalent.

Upvotes: 2

Related Questions