Tuple vs Dictionary differences

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

    Major difference:

    • If you need to return multiple values from a method you can use tuple.
    • Tuple won't need any key value pairs like Dictionary.
    • A tuple can contain only the predefined number of values, in dictionary there is no such limitation.
    • A tuple can contain different values with different datatype while a dictionary can contain only one datatype value at a time
    • Tuples are particularly useful for returning multiple values from a function. A dictionary can be used as a model object.

    There are two types of Tuple:

    1 Named Tuple

    In Named tuple we assign individual names to each elements.

    Define it like:

    let nameAndAge = (name:"Midhun", age:7)
    

    Access the values like:

    nameAndAge.name
    nameAndAge.age
    

    2 Unnamed Tuple

    In unnamed tuple we don't specify the name for it's elements.

    Define it like:

    let nameAndAge = ("Midhun", 7)
    

    Access the values like:

    nameAndAge.0
    nameAndAge.1
    

    or

    let (theName, thAge) = nameAndAge
    theName
    thAge
    

    Reference:

    Tuple

    Tuples enable you to create and pass around groupings of values. You can use a tuple to return multiple values from a function as a single compound value.

    You can check more about Tuple in Swift Programming Language

    Dictionary

    A dictionary is a container that stores multiple values of the same type. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary

    You can check more about Dictionary in Swift CollectionTypes

提交回复
热议问题