Tuple vs Dictionary differences

前端 未结 6 970
悲&欢浪女
悲&欢浪女 2021-01-30 10:56

Can someone please explain what the major differences there are between Tuples and Dictionaries are and when to use which in Swift?

6条回答
  •  余生分开走
    2021-01-30 11:34

    Tuples are fixed-length things. You can’t add an extra element to a tuple or remove one. Once you create a tuple it has the same number of elements – var t = (1,2) is of type (Int,Int). It can never become (1,2,3), the most you could do is change it to, say, (7,8). This is all fixed at compile-time.

    You can access the elements via their numeric positions like this

    t.0 + t.1  // with (1,2), would equal 3
    t.0 = 7
    

    Arrays are variable length: you can start with an array var a = [1,2], and then add an entry via a.append(3) to make it [1,2,3]. You can tell how many items with a.count. You can access/update elements via a subscript: a[0] + a[2] // equals 4

    You can name the elements in tuples:

    var n = (foo: 1, bar: 2)
    

    Then you can use those names:

    n.foo + n.bar  // equals 3
    

    This doesn’t remove the ability to access them by position though:

    n.0 + n.1  // equals 3 
    

    But these names, once set, are fixed at compile time just like the length:

    n.blarg  // will fail to compile
    

    This is not the same as dictionaries, which (like arrays), can grow or shrink:

    var d = [“foo”:1, “bar”:2]
    d[“baz”] = 3; 
    d[“blarg”] // returns nil at runtime, there’s no such element    
    

提交回复
热议问题