Swift optional binding with tuples

后端 未结 4 1673
挽巷
挽巷 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:23

    You have to use a switch as the other answer points out. However, if you're only going to check both values, an if without Optional Binding is actually shorter and easier-to-read.

    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 (user, pass) {
        case let (.Some(user), .Some(pass)): print("this works: \(user), \(pass)")
        default: ()
    }
    

提交回复
热议问题