简体   繁体   English

Swift 可选的元组绑定

[英]Swift optional binding with tuples

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.我试图在 Swift 的 IF 语句中使用元组作为可选绑定,但它不会编译,并且该错误消息没有帮助。 Why doesn't the following compile?为什么以下不编译?

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

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

or this或这个

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

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

edit: as of Swift 1.2 in Xcode 6.3, you can now do:编辑:从 Xcode 6.3 中的 Swift 1.2 开始,您现在可以执行以下操作:

if let user = user, pass = pass { }

to bind multiple unwrapped optional values.绑定多个未包装的可选值。

You can't use optional let binding that way.您不能以这种方式使用可选的 let 绑定。 let test = (user,pass) won't compile since (user,pass) is not an optional – it's a tuple that contains optionals. let test = (user,pass)不会编译,因为(user,pass)不是可选的——它是一个包含可选的元组。 That is, it's an (Int?,Int?) not an (Int,Int)?也就是说,它是(Int?,Int?)不是(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
}

In Swift 2 with optional pattern matching you can write在带有可选模式匹配的 Swift 2 中,您可以编写

if case let (user?, pass?) = (user, pass) { }

This is especially useful if, for example, (user, pass) is a tuple stored in a variable.例如,如果 (user, pass) 是存储在变量中的元组,这将特别有用。

You have to use a switch as the other answer points out.正如另一个答案指出的那样,您必须使用switch However, if you're only going to check both values , an if without Optional Binding is actually shorter and easier-to-read.但是,如果您只想检查两个值if没有可选绑定的if实际上更短且更易于阅读。

if (user != nil && pass != nil) {
    print("this works: \(user!), \(pass!)")
}

The switch is goofy and hard-to-read (taken from other answer), but if you're going to use the other cases (nil-some, some-nil, nil-nil) then it might be worth it.switch很笨拙且难以阅读(取自其他答案),但如果您打算使用其他情况(零一些,一些零,零零)那么它可能是值得的。

switch (user, pass) {
    case let (.Some(user), .Some(pass)): print("this works: \(user), \(pass)")
    default: ()
}
if case let (.some(user), .some(pass)) = (optionalUser, optionalPass) {
    print("user \(user). pass \(pass)")
}

Let's say we have tuple having two optional Ints.假设我们有两个可选的 Int 元组。 To unwrap it we can optionally cast it to (Int, Int) using as?.要解开它,我们可以选择使用 as? 将其强制转换为 (Int, Int)。 If any of them is nil then it won't be able to cast it.如果其中任何一个为零,那么它将无法投射它。 If it does we will get unwrapped values from that tuple.如果是这样,我们将从该元组中获得未包装的值。

let tuple: (Int?, Int?) = (1, 2)
if let (value1, value2) = tuple as? (Int, Int) {
     print("value1: \(value1), value2: \(value2)")
} 

//value1: 1, value2: 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM