Ios 无法从字符串中删除“可选”

Ios 无法从字符串中删除“可选”,ios,swift,swift2,optional,Ios,Swift,Swift2,Optional,下面是我的片段 // MARK: - Location Functions func getCurrentLocation() -> (String!, String!) { let location = LocationManager.sharedInstance.currentLocation?.coordinate return (String(location?.latitude), String(location?.longitude))

下面是我的片段

// 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)
    }
虽然我用纬度打开可选的!还有经度!,它打印我可选37.33233141,可选122.0312186

我打破了我的头,以消除可选的绑定

你的线路

(String(location?.latitude), String(location?.longitude))
是罪魁祸首

当您调用字符串时,它会生成一个内容字符串,但在这里,您的内容是可选的,所以您的字符串是可选的。。。由于可选类型符合StringLiteralConvertible,Optionalvalue将变为Optionalvalue

以后不能删除它,因为它现在是表示可选字符串的文本,而不是可选字符串


解决方案是首先完全展开位置?纬度和位置?经度。

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

成功了

更改为此返回字符串位置?纬度!,位置?经度!不过,你应该添加一些检查,以确保它们不为零,否则你的程序将崩溃。这就是为什么我们中有这么多人遇到问题的原因。我希望我能和更多的人分享这个。反应很好!