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

标签 if-statement swift option-type

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

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 查询合二为一。所以它会是这样的:

if let latitudeDouble = latitude as? Double, longitudeDouble = longitude as? Double {
    // do stuff here
}

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

最佳答案

Swift 3 更新:

以下将在 Swift 3 中工作:

if let latitudeDouble = latitude as? Double, let longitudeDouble = longitude as? Double {
    // latitudeDouble and longitudeDouble are non-optional in here
}

请务必记住,如果尝试的可选绑定(bind)之一失败,则不会执行 if-let block 中的代码。

注意:子句不一定都是“let”子句,您可以使用逗号分隔的任何一系列 bool 检查。

例如:

if let latitudeDouble = latitude as? Double, importantThing == true {
    // latitudeDouble is non-optional in here and importantThing is true
}

Swift 1.2:

Apple 可能已经阅读了您的问题,因为您希望的代码可以在 Swift 1.2(今天处于测试阶段)中正确编译:

if let latitudeDouble = latitude as? Double, longitudeDouble = longitude as? Double {
    // do stuff here
}

Swift 1.1 及更早版本:

好消息是——您完全可以做到这一点。两个值的元组上的 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")
}

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

关于if-statement - 在 Swift 中的 if 语句中使用多个 let-as,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24592004/

相关文章:

PHP Mysql - 将数据库 ID 中的所有值加 1,下一个值减去 1

Swift - 从卷中的最后一张照片更新 UIButton 图像

java - 在 Java 8 中,转换 Optional.empty 中空字符串的 Optional<String>

string - 在 Rust 中匹配 Option 静态字符串文字

ios - 无法打开 NSError

javascript - 为函数接受 2 个参数且只给出一个参数时设置默认参数 - Javascript

javascript - 为什么我的 javascript if 语句不以数组为目标?

linux - Bash 脚本条件

ios - 通过数组添加的 View 的约束

ios - 在应用程序委托(delegate)的 didRegisterForRemoteNotificationsWithDeviceToken 上调用时,IBOutlet 似乎为零