Tuple vs Dictionary differences

前端 未结 6 1215
悲&欢浪女
悲&欢浪女 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:26

    • A tuple is completely predefined: it can only have the names and number of values you've predefined for it, though they can be different value types, and they don't have to have names. And the names are literals.

    • A dictionary can have any number of key-value pairs, of one value type. And the keys can be referred to through variables.


    Here's a tuple (with names):

    typealias MySillyTuple = (theInt:Int, theString:String)
    

    That's it. There is one Int called theInt, one String called theString, and that is exactly what it must have, no more, no less. And the only way to access the values by name is as a literal: t.theInt. If you have a string "theInt", you can't use it to access t.theInt.

    Here's a Dictionary:

    var d = [String:String]()
    

    Now d can have any number of keys, and any keys, from none to a gazillion. And the keys can be specified using string variables; you don't have to know in advance what a key will be. And all the values must be strings.

    So basically I would say a tuple is nothing like a dictionary. A dictionary is a complex beast for look up by dynamic keys. A tuple is just a value that is more than one value.

提交回复
热议问题