Why to use tuples when we can use array to return multiple values in swift

前端 未结 4 1840
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 13:51

Today I was just going through some basic swift concepts and was working with some examples to understand those concepts. Right now I have completed studying tuples.

4条回答
  •  独厮守ぢ
    2020-12-02 14:04

    For example, consider this simple example:

    enum MyType {
        case A, B, C
    }
    
    func foo() -> (MyType, Int, String) {
        // ...
        return (.B, 42, "bar")
    }
    
    let (type, amount, desc) = foo()
    

    Using Array, to get the same result, you have to do this:

    func foo() -> [Any] {
        // ...
        return [MyType.B, 42, "bar"]
    }
    
    let result = foo()
    let type = result[0] as MyType, amount = result[1] as Int, desc = result[2] as String
    

    Tuple is much simpler and safer, isn't it?

提交回复
热议问题