Cannot assign value of type 'String?' to t

2019-08-03 09:08发布

问题:

I'm a newbie to Swift and xCode so apologies if some of my terminology is incorrect.

I've just started learning CoreData and am attempting to produce a basic function where users can create a 'location.'

I set up the data model with the attributes name (type = string), latitude (type = double) and longitude (type = double).

I've set up a TableViewController (which is working fine) with a segue to another Controller which is set up to enable people to enter a name, latitude and longitude.

As far as I can tell, everything is set up correctly except for the two lines of code which read the text fields I connected to the Latitude and Longitude outlet. This code is contained in the AddLocationController.

Any help would be appreciated!

@IBOutlet var nameTextField:UITextField!
@IBOutlet var latitudeTextField:UITextField!
@IBOutlet var longitudeTextField:UITextField!

@IBAction func save(sender: AnyObject) {
if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
        location = LocationMO(context: appDelegate.persistentContainer.viewContext)

        location.name = nameTextField.text

        // This is where the error occurs
         location.latitude = latitudeTextField.text
         location.longitude = longitudeTextField.text

    print("saving data to context ...")
    appDelegate.saveContext()

    }

    dismiss(animated: true, completion: nil)

    }
}

回答1:

Just try in this way

location.latitude = Double(latitudeTextField.text)
 location.longitude = Double(longitudeTextField.text)

Example given below

let str:String = "5.0"
 if let myd:Double = Double(str)
 {
         print(myd)
  }


回答2:

Your problem is that you are trying to give a string value to a double. In order to solve this and avoid your application to crash if the text cannot be converted to double use this:

if let lat = latitudeTextField.text as? Double{
 location.latitude = lat

}
if let long = longitudeTextField.text as? Double{
 location.longitude = long
}

In this way if one of the texts couldn't be converted to a double your app will not crash but location longitude or latitude will stay nill.