无法从String中删除“Optional”
以下是我的片段
// MARK: - Location Functions func getCurrentLocation() -> (String!, String!) { let location = LocationManager.sharedInstance.currentLocation?.coordinate return (String(location?.latitude), String(location?.longitude)) } func setCurrentLocation() { let (latitude, longitude) = getCurrentLocation() let location = "\(latitude!),\(longitude!)" print(location) }
虽然我用latitude!
打开可选项latitude!
和longitude!
,它打印出我Optional(37.33233141),Optional(-122.0312186)
我正在打破我的头,删除Optional绑定。
你的路线
(String(location?.latitude), String(location?.longitude))
是罪魁祸首。
当你调用String()
它会生成一个内容的String
,但是这里你的内容是一个Optional,所以你的String是"Optional(...)"
(因为Optional类型符合StringLiteralConvertible, Optional(value)
变成"Optional(value)"
)。
您以后无法删除它,因为它现在是表示Optional的文本 ,而不是可选字符串。
解决方案是首先完全打开location?.latitude
和location?.longitude
。
关于Eric D的评论,我将片段修改为
// MARK: - Location Functions func getCurrentLocation() -> (String, String) { let location = LocationManager.sharedInstance.currentLocation?.coordinate let numLat = NSNumber(double: (location?.latitude)! as Double) let latitude:String = numLat.stringValue let numLong = NSNumber(double: (location?.longitude)! as Double) let longitude:String = numLong.stringValue return (latitude, longitude) } func setCurrentLocation() { let (latitude, longitude) = getCurrentLocation() let location = "\(latitude),\(longitude)" print(location) }
有效!