尝试从文本字段获取纬度和经度时,无法转换类型的值

时间:2018-11-13 02:15:09

标签: ios swift core-location

Image of the project

我的代码不起作用。 当用户输入经度和纬度时,它应该转到“地图”,但会引发错误。仅当我对纬度和经度进行硬编码时,它才有效。

ng generate akasuaptics:page --name=test

3 个答案:

答案 0 :(得分:3)

类型不正确。

更改 let latitude:CLLocationDegrees = Latitude_buttonDouble(Latitude_button.text ?? "") ?? 0

longitude

let longitude:CLLocationDegrees = Double(Longitude.text ?? "") ?? 0

此外,您的名称约定非常正确。应该类似于latitudeButtonlongitude

答案 1 :(得分:3)

在行let latitude:CLLocationDegrees = Latitude_button上,您试图将类型UITextField的变量分配给类型CLLocationDegrees的变量。

您需要做的是从文本字段中获取文本,然后尝试将其转换为数字,然后将该数字分配给变量。

guard let latitude = CLLocationDegrees(Latitude_button.text!),
      let longitude = CLLocationDegrees(Longitude.text!) else {
    // show some sort message to the user that the values are invalid
    return
}

答案 2 :(得分:0)

有些东西可能会帮助您入门,就像我去过那里一样

  1. 在Swift中,变量位于camelCase中,按照惯例,变量声明应远离snake_caseCapitalized。我会为您的@IBOutlets ...

    做这样的事情
    @IBOutlet weak var longitudeField: UITextField!
    @IBOutlet weak var latitudeField: UITextField!
    
  2. UITextFields中包含Strings,但是在您的showMeWhere方法中,您试图将UITextField分配给CLLocationDegrees

    • UITextField具有一个名为text的属性。那就是您想要的,而不是字段...您想要字段中的文本。

    • CLLocationDegreestypealias的{​​{1}} ...因此将Double转换为String之前的问题。 / p>

这是您的操作方式:

Double