Reputation: 559
An example in swift tour in https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
The final result of occupations is :
["Kaylee": "Mechanic", "Jayne": "Public Relations", "Malcolm": "Captain"]
My question:
Upvotes: 0
Views: 393
Reputation: 62062
The existing answers are highly likely to be confusing depending on what sort of programming background you come from.
var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations"
Given that code snippet, the type of occupations
is a Swift Dictionary. As the other answers point out, a dictionary, in Swift, is a collection of key-value pairs.
Other languages have a similar data structure, but may refer to it by a different name.
The list could go on. But these all represent roughly the same data structure: a store of key & value pairs.
In Swift, dictionaries do not have an order. Any perceived ordering you notice from printing or iterating over items in a dictionary is just that--perceived. It should not be relied on.
If you need an ordered dictionary, you will need to implement it on your own. Although I'm sure someone has probably already implemented it and you can find it on github. A very simple implementation for an ordered pairs of data could simply involve an array of tuples, but you wouldn't be able to do the same key look up you can with dictionaries.
What is important here is that there is no defined order for data in a Swift dictionary, so any perceived ordering that is happening should not be relied on.
Upvotes: 3
Reputation: 131426
To turn Eric and Luk's comments into an official answer:
Your var 'occupations' is a Swift Dictionary object.
A Dictionary in Swift (and Objective-C as well) does not have any order at all. It is an "unordered collection."As Luk says, it's a key-value store. You save and retrieve values using a key.
Your questions:
It's not called a Map in iOS, but it the equivalent of a map in other languages like C#, C++, and Java.
Dictionaries do no have any order whatsoever.
Upvotes: -1
Reputation: 1
"Map" is a function that takes a list (such as the keys or values of "occupations") and returns an array of the original list with a function applied to it.
For example
(0..<4).map({$0 + 1})
Returns an array of [1, 2, 3, 4] because the $0 is Swift shorthand for "the value of the original array that am currently applying this function to.
Upvotes: 0