【问题标题】:Unable to remove "Optional" from String无法从字符串中删除“可选”
【发布时间】:2016-02-10 11:43:38
【问题描述】:

下面是我的sn-p

// 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!longitude! 解开可选的包装,但它会打印我Optional(37.33233141),Optional(-122.0312186)

我正在打破我的头来删除可选绑定。

【问题讨论】:

  • 改成这个return (String(location?.latitude!), String(location?.longitude!)),你应该添加一些检查以确保它们不是nil,否则你的程序将会崩溃。

标签: ios swift swift2 optional


【解决方案1】:

你的线路

(String(location?.latitude), String(location?.longitude))

是罪魁祸首。

当您调用String() 时,它会生成内容的String,但这里您的内容是可选的,因此您的字符串是"Optional(...)"(因为可选类型符合StringLiteralConvertible,Optional(value) 变为"Optional(value)" )。

您不能稍后将其删除,因为它现在是 text 表示一个 Optional,而不是 Optional String。

解决方案是先完全解开location?.latitudelocation?.longitude

【讨论】:

  • 这就是我们这么多人遇到问题的原因。我希望我能与更多的人分享这个。很好的反应!
【解决方案2】:

关于 Eric D 的评论,我将 sn-p 修改为

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

成功了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2014-05-13
    • 2013-04-17
    • 2015-09-22
    • 2017-04-30
    相关资源
    最近更新 更多