Swift元组的可选绑定 [英] Swift optional binding with tuples

查看:76
本文介绍了Swift元组的可选绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Swift的IF语句中使用元组作为可选绑定,但是它不会编译,并且该错误消息没有什么用.为什么以下代码无法编译?

I'm trying to use a tuple as an optional binding in an IF statement in Swift but it won't compile and that error message is less than helpful. Why doesn't the following compile?

let user:String? = "billy"
let pass:String? = "password"

if let test = (user?,pass?){
    print("this works")
}

或这个

let user:String? = "billy"
let pass:String? = "password"

if let test = (user,pass){
    print("this works")
}

推荐答案

从Xcode 6.3中的Swift 1.2开始,您现在可以执行以下操作:

edit: as of Swift 1.2 in Xcode 6.3, you can now do:

if let user = user, pass = pass { }

绑定多个未包装的可选值.

to bind multiple unwrapped optional values.

您不能以这种方式使用可选的let绑定. let test = (user,pass)不会编译,因为(user,pass)不是可选的–它是一个包含可选的元组.也就是说,它是(Int?,Int?)而不是(Int,Int)?.

You can't use optional let binding that way. let test = (user,pass) won't compile since (user,pass) is not an optional – it's a tuple that contains optionals. That is, it's an (Int?,Int?) not an (Int,Int)?.

这应该做您想要的,并允许您同时绑定两个项目:

This should do what you want and allows you to bind two items simultaneously:

switch (user, pass) {
    case let (.Some(user), .Some(pass)):
        print("this works: \(user), \(pass)")
    default: ()  // must handle all cases
}

这篇关于Swift元组的可选绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆