在Swift的if语句中使用多个let-as

我要从字典中解开两个值,在使用它们之前,我必须将它们强制转换并测试正确的类型。这是我想出的:

var latitude : AnyObject! = imageDictionary["latitude"]

var longitude : AnyObject! = imageDictionary["longitude"]

if let latitudeDouble = latitude as? Double {

if let longitudeDouble = longitude as? Double {

// do stuff here

}

}

但是我想将两个查询打包在一起。这样就可以了:

if let latitudeDouble = latitude as? Double, longitudeDouble = longitude as? Double {

// do stuff here

}

该语法不起作用,所以我想知道是否有一种漂亮的方法可以做到这一点。

回答:

以下内容将在Swift 3中运行:

if let latitudeDouble = latitude as? Double, let longitudeDouble = longitude as? Double {

// latitudeDouble and longitudeDouble are non-optional in here

}

请务必记住,如果尝试的可选绑定之一失败,if-let则不会执行该块内的代码。

注意:这些子句不必全部都是’let’子句,您可以将任何一系列布尔检查用逗号分隔。

例如:

if let latitudeDouble = latitude as? Double, importantThing == true {

// latitudeDouble is non-optional in here and importantThing is true

}

Apple可能已经读过您的问题,因为您希望的代码可以在Swift 1.2(今天为beta)中正确编译:

if let latitudeDouble = latitude as? Double, longitudeDouble = longitude as? Double {

// do stuff here

}


这是个好消息-您完全可以做到这一点。两个值的元组上的switch语句可以使用模式匹配将它们都同时转换Double为:

var latitude: Any! = imageDictionary["latitude"]

var longitude: Any! = imageDictionary["longitude"]

switch (latitude, longitude) {

case let (lat as Double, long as Double):

println("lat: \(lat), long: \(long)")

default:

println("Couldn't understand latitude or longitude as Double")

}

此版本的代码现在可以正常工作。

以上是 在Swift的if语句中使用多个let-as 的全部内容, 来源链接: utcz.com/qa/422379.html

回到顶部