Swift optional binding with tuples

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

    Let's say we have tuple having two optional Ints. To unwrap it we can optionally cast it to (Int, Int) using as?. 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
    

提交回复
热议问题