Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple vs Dictionary differences

Tags:

ios

swift

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

like image 396
Phil Avatar asked Dec 24 '14 03:12

Phil


People also ask

What are the difference between tuple and dictionary class 11?

The tuples refer to the collections of various objects of Python separated by commas between them. The sets are an unordered collection of data types. These are mutable, iterable, and do not consist of any duplicate elements. In Python, the dictionary refers to a collection (unordered) of various data types.

What is the difference between tuple and dictionary C#?

Tuples have structure, lists have order. A dictionary is a key-value store. It is not ordered and it requires that the keys are hashable. It is fast for lookups by key.

Which is faster tuple or dictionary?

It is well-known that in Python tuples are faster than lists, and dicts are faster than objects.


1 Answers

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

like image 83
Midhun MP Avatar answered Sep 22 '22 13:09

Midhun MP