Unable to remove “Optional” from String

2020-05-09 17:01发布

问题:

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!