无法分配类型为'String'的值?输入“ Double”错误 [英] Cannot assign value of type 'String?' to type 'Double' error

查看:83
本文介绍了无法分配类型为'String'的值?输入“ Double”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift和xCode的新手,因此如果我的某些术语不正确,我深表歉意。

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

我刚刚开始学习CoreData并试图生成一个用户可以在其中创建位置的基本功能。

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

我使用属性名称(类型=字符串),纬度(类型= double)和经度建立数据模型(类型=两倍)。

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

我已经建立了一个TableViewController(工作正常),并与另一个Controller进行了连接,该Controller的设置使人们可以输入名称,纬度和经度。

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.

据我所知,除读取与纬度相关的文本字段的两行代码外,其他所有内容均已正确设置和经度插座。该代码包含在AddLocationController中。

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.

任何帮助将不胜感激!

@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)

    }
}


推荐答案

只需尝试这种方式

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)
  }

这篇关于无法分配类型为'String'的值?输入“ Double”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆