无法摆脱Optional()字符串 [英] Cannot get rid of Optional() string
本文介绍了无法摆脱Optional()字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试更新服务器上的用户位置
I am trying to update users location on server
使用此功能
func updateloc(lat : String?, long : String?) {
/code...
let data = "lat=\(lat!)&long=\(long!)"
}
这是委托人
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
updateloc(String(manager.location?.coordinate.latitude), long: String(manager.location?.coordinate.longitude))
}
对于 lat
和 long
变量并且无法摆脱它。
I have Optional("") for lat
and long
variables and cannot get rid of it.
有什么想法吗?
推荐答案
如果解开像这样的纬度和经度值...
If you unwrap the latitude and longitude values like this...
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let lat = manager.location?.coordinate.latitude,
let long = manager.location?.coordinate.longitude {
updateloc(String(lat), long: String(long))
}
}
...那么您可以完全避免使用可选项在 updateloc
函数中:
...then you can avoid optionals altogether in the updateloc
function:
func updateloc(lat : String, long : String) {
// code...
let data = "lat=\(lat)&long=\(long)"
}
originalUser2
是正确的...您应该养成安全地解开可选选项的习惯,除非您有充分理由强制解开它们。并且只是试图摆脱可选变量以便代码可以编译不是一个好理由。
originalUser2
is right...you should get in the habit of safely unwrapping optionals unless you have a really good reason for force-unwrapping them. And just trying to get rid of the optional so the code will compile is not a good reason.
这篇关于无法摆脱Optional()字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文