Can someone please explain what the major differences there are between Tuples and Dictionaries are and when to use which in Swift?
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.