xcode 无法分配“字符串”类型的值?输入“双重”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43344796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot assign value of type 'String?' to type 'Double' error
提问by joshlorschy
I'm a newbie to Swift and xCode so apologies if some of my terminology is incorrect.
我是 Swift 和 xCode 的新手,如果我的一些术语不正确,我深表歉意。
I've just started learning CoreData and am attempting to produce a basic function where users can create a 'location.'
我刚刚开始学习 CoreData 并且正在尝试生成一个基本功能,用户可以在其中创建“位置”。
I set up the data model with the attributes name (type = string), latitude (type = double) and longitude (type = double).
我使用属性名称(type = string)、纬度(type = double)和经度(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.
我已经设置了一个 TableViewController(它工作正常)与另一个控制器的 segue,该控制器设置为使人们能够输入名称、纬度和经度。
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.
据我所知,除了读取我连接到纬度和经度插座的文本字段的两行代码之外,一切都设置正确。此代码包含在 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)
}
}
回答by Vinod Kumar
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)
}
回答by Jaafar Barek
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.
通过这种方式,如果其中一个文本无法转换为双精度,您的应用程序不会崩溃,但位置经度或纬度将保持为零。