Can someone please explain what the major differences there are between Tuples and Dictionaries are and when to use which in Swift?
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.
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
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
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
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
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
A dictionary is made up of key-value sets. A tuple is made for passing grouped values.
Dictionaries:
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.
A dictionary should be used for creating lists of associated objects. An example use would be a dictionary of players and their scores:
var scoreDictionary = ["Alice" : 100, "Bob" : 700]
Tuples:
Tuples group multiple values into a single compound value.
A tuple should be used for passing groups of values. They are similar to arrays, but are fixed-length and immutable. An example use might be a tuple representing a 3-dimensional point:
var myPoint = (10, 12, 14)
As you can see there are many cases in which you would use a dictionary and many cases in which you would use a tuple. Each has its own specific purpose.
Tuples are compound values, and can be useful for functions returning several values from a function. e.g. (from the Apple Docs):
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
This function returns a tuple containing min, max and sum. These values can be accessed either by name or position:
let statistics = calculateStatistics([5, 3, 100, 3, 9])
var sum:Int = statistics.sum
var sum2:Int = statistics.2
Dictionaries are "lookup" data types. They return an object for a given key. For example the following code:
let font:NSFont = NSFont(name: "AppleCasual", size: 18.0)!
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.LeftTextAlignment
let textColor:NSColor = NSColor(calibratedRed: 1.0, green: 0.0, blue: 1.0, alpha: 1.0)
let attribs = [NSFontAttributeName: font,
NSForegroundColorAttributeName: textColor,
NSParagraphStyleAttributeName: textStyle]
let color = attribs[NSForegroundColorAttributeName]
println("color = \(color)")
Will print:
color = Optional(NSCalibratedRGBColorSpace 1 0 1 1)
Dictionaries are useful for many things and are required for some functions. For example (after the code above):
let testString:NSString = "test String"
var img:NSImage = NSImage(size: NSMakeSize(200,200))
img.lockFocus()
testString.drawAtPoint(NSMakePoint(0.0, 0.0), withAttributes: attribs)
img.unlockFocus()
In this code drawAtPoint uses the dictionary attribs to lookup the parameters it needs. The parameters don't need to be in any specific order because drawAtPoint will lookup the values it needs by using the correct key.
Dictionaries and tuples are similar, but not quite the same. In the code above the dictionary returned an Optional type:Optional(NSCalibratedRGBColorSpace 1 0 1 1)
If we use a tuple for the same purpose:
var attribTuple = (font:NSFont(name: "AppleCasual", size: 18.0), color:NSColor(calibratedRed: 1.0, green: 0.0, blue: 1.0, alpha: 1.0))
println("tupleColor = \(attribTuple.color)")
Prints:
tupleColor = NSCalibratedRGBColorSpace 1 0 1 1
Not the optional type the dictionary did.
Dictionary
is Collection Type
, Tuple
is Compound type
.Dictionary
is Key Value
type, Tuple
is Comma separated list of multiple types
Dictionary:
var dictionary = ["keyone": "value one", "keytwo": "Value Two"]
Tuple:
let someTuple: (Double, Double, String, (Int, Int)) = (3.14159, 2.71828, "Hello", (2, 3))