Swift optional binding with tuples

后端 未结 4 1663
挽巷
挽巷 2021-01-04 04:44

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

4条回答
  •  轮回少年
    2021-01-04 05:29

    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.

    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
    }
    

提交回复
热议问题