Collection Types are structs not classes.
Same like objC Array (Ordered collection of values), Set (unordered collection of unique values) and Dictionary(Key- value mapping).
Swift collection type implemented as generic collection(template) and they are bridged to objC foundation’s NSArray. (Bridging is done with as keyword).
Array:
Some Ex:
var someInts = [Int]()
let arraInt :Array<Int>
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
shoppingList[4...6] = ["Bananas", "Apples"]
for item in shoppingList {
print(item)
}
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}
Set: Storing type must be hashable .(Hashable needs to conform to Hashable protocol. Hashable consforms to equatable so == needs to be implemented.). Set has set property like intersect, subset, union etc
Some Ex
var letters = Set<Character>()
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
for genre in favoriteGenres {
print("\(genre)")
}
Dictionary :(Key must be hashable)
Some Ex:
var namesOfIntegers = [Int: String]()
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
for airportName in airports.values {
print("Airport name: \(airportName)")
}
Items in Dictionary may not be iterated in same order in which they inserted.
0 comments:
Post a Comment