无法删除"可选"来自String

时间:2016-02-10 11:43:39

标签: ios swift swift2 optional

以下是我的代码段

function keyGenerator(len:Number):String
{
    function randomRange(minNum:Number, maxNum:Number):Number
    {
        return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
    }
    var hexArray = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
    var key = "";
    for (var i=0; i<len; i++)
    {
        key +=  hexArray[randomRange(0,hexArray.length-1)];
    }
    return key;
}

虽然我使用trace(keyGenerator(16)); // 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!

我正在试图删除Optional绑定。

2 个答案:

答案 0 :(得分:4)

你的行

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

是罪魁祸首。

当您致电String()时,它会生成String内容,但此处您的内容是可选的,因此您的字符串为"Optional(...)"(因为Optional类型符合StringLiteralConvertible,{ {1}}变为Optional(value))。

您之后无法将其删除,因为它现在是 text ,表示可选字符串,而不是可选字符串。

解决方案是首先完全展开"Optional(value)"location?.latitude

答案 1 :(得分:-2)

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

有效!