Unable to remove “Optional” from String

六眼飞鱼酱① 提交于 2019-12-20 07:43:07

问题


Below is my snippet

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

Though I unwrap optional using latitude! and longitude!, it prints me Optional(37.33233141),Optional(-122.0312186)

I am breaking my head to remove the Optional binding.


回答1:


Your line

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

is the culprit.

When you call String() it makes a String of the content, but here your content is an Optional, so your String is "Optional(...)" (because the Optional type conforms to StringLiteralConvertible, Optional(value) becomes "Optional(value)").

You can't remove it later, because it's now text representing an Optional, not an Optional String.

The solution is to fully unwrap location?.latitude and location?.longitude first.




回答2:


With respect to Eric D's comment, I modified the snippet to

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

It worked!



来源:https://stackoverflow.com/questions/35314279/unable-to-remove-optional-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!