Swift Collection Types

Collection Types

  • Swift provides three primary collections, known as Array, Set, and Dictionary
  • Arrays store values of the same type in a ordered list
  • Sets are unordered colletions of unique values
  • Dictionarys are unordered collections of key-value associations
  • you cannot insert a value of wrong type into a colletion

Arrays

Array Type Shorthand Syntax

  • the type of an Array in Swift is written in full as Array<Element>, Element is the type of values the array allows to store
  • you can also write the type of an array in shorthand form as [Element], and the shorthand form is prefered.

Creating An Empty Array

  • you can create an empty array of a certain type using initializer syntax
var someInts = [Int]()
  • if the type of an array is provided, you can make it empty by assigning the array with an empty array literal, which is written as []
someInts.append(3)  //[3]
someInts = []       //[]

Creating An Array With A Default Value

  • Swift’s Array provides an initializer for creating an array of a certain size with all of its values set to the same default value
var threeDoubles = Array(repeating: 0.0, count: 3)

Creating An Array By Adding Two Arrays Together

  • you can create a new array by adding 2 existing arrays with compatible types with the additional operator.
var twoDouble = Array(repeating: 1.1, count: 2)
var threeDouble = Array(repeating: 0.0, count: 3)
var fiveDouble = twoDouble + threeDouble

Creating An Array With An Array Literal

  • you can create an array with an array literal, which is written as a list of valus, seperated by commas, surrounded by a pair of square brackets
var shoppingList: [String] = ["Eggs", "Milk"]
  • you don’t have to write the type of an array, if you are initializing an array with an array literal containing values of the same type
var shoppingList = ["Eggs", "Milk"]

Accessing And Modifying An Array

  • you can access and modify an array by using its methods, properties or subscript syntax
  • to find out the numbers of an array, check its read-only property count
print("shoppingList have \(shoppingList.count) items")
  • to check whether the count of an array is 0, use the isEmpty property
if shoppingList.isEmpty {
    print("empty")
} else {
    print("not empty")
}
  • you can add a new item to the end of the array by calling the append(_😃 method
shoppingList.append("Flour")
  • you can append an array of one or more values of compatible type by using addition assignent operator
shoppingList += ["Baking Power"]
  • retrieve a value from an array by using subscript syntax
let oneItem = shoppingList[0]
  • you can use subscript syntax to change an existing array
shoppingList[0] = "Six Eggs"
  • you can use subscript syntax to change a range of values at once, even if the replacement set of values has a different length than the range you are replacing
shoppingList[0...2] = ["Bananas", "Apples"]
  • insert a value into an array at a specific index, by calling the insert(_:at:) method
shoppingList.insert("Maple", at: 0)
  • remove a value from an array at a specific index, by calling the remove(at:) method
shoppingList.remove(at: 0)

note: if you are trying to accessing or modifying a value for a specific index that is out of the array’s bounds, you will trigger a runtime error. before using an index, check whether it is valid by comparing it to the count property

  • use the removeLast() method to remove the last item from an array, and the method returns the removed item
let removedItem = shoppingList.removeLast()

Iterating Over An Array

  • you can iterate over the entire set of values in an array with the for-in loop
for item in shoppingList {
    print(item)
}
  • use enumerated() method to get the integer index and the value of each item. this method returns a tuple composed of an integer and an item.
for (index, item) in shoppingList {
    print("index: \(index), item: \(item)")
}

Sets

  • a set stores values of the same type with no defined ordering

Hash Value For Set Types

  • to be stored in a set, a type must provide a way to compute the hash value for itself
if a.hashValue == b.hashValue {
    print("they are equal")
}
  • make types that have no hash value comform to the Hashable protocol to use them as set value types or dictionary key value types

Set Type Syntax

  • the type of a set is written as Set

Creating and Initializing an Empty Set

var letters = Set<Character>()

Creating a Set with an Array Literal

  • you can initialize a set with an array literal
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
  • the type Set must be explicitly declared, because a set type cannot be inferred from an array literal alone. if so, it is a array, not a set.
  • but you don’t have to write the type of set’s elements if the elements’ type are the same
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

Accessing and Modifying a Set

  • you can find out the number of values in a set by using the count property
print(favoriteGenres.count)
  • you can find out whether the count of a set is equal to 0 by using the isEmpty property
if favoriteGenres.isEmpty {
    print("it is empty")
} else {
    print("it is not empty")
}
  • you can add a new item into a set by using the insert(_😃 method
favoriteGenres.insert("Jazz")
  • you can remove an item from a set by calling the remove(_😃 method
  • if the item is part of the set, then remove it and return the value of an optional type
  • if not, return nil
if let removedItem = favoriteGenres.remove("Rock") {
    print(removedItem)
} else {
    print("there is no Rock")
}
  • you can remove all items from a set by calling the removeAll() method
favoriteGenres.removeAll()
print(favoriteGenres.count)
  • you can check whether a set contains a particular item

Dictionary

  • a dictionary stores associations between keys of the same type and values of the same type in a collection in no defined ordering
  • each value associates with a unique key which acts as an identifier for the value

Dictionary Syntax

  • the type of a dictionary is written in full as Dictionary<KeyType: ValueType>
  • the type of key must conform to the Hashable protocol, like a set’s value type
  • the type of a dictionary is also written in shortcut form as [KeyType: ValueType]

Creating An Empty Dictionary

  • you can use an initializer to create an empty dictionary
var nameOfIntegers = [Int: String]()
  • you can use an empty dictionary literal to create an empty dictionary
var emptyDictionary: [Int: String] = [:]

note: the type information must be provided

Creating A Dictionary With A Dictionary Literal

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
  • you don’t have to write the type of the dictionary if you initialize it with a dictionary literal whose keys and values have consistent types
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

Accessing And Modifying A Dictionary

  • you can find out the number of the items of a dictionary by checking its count property
print("\(airports.count)")
  • you can check whether the count property is 0 by using the isEmpty property
if airports.isEmpty {
	print("the dictionary is empty")
} else {
	print("the dictionary is not empty")
}
  • you can add a new item to a dictionary with subscript syntax
airports["LHR"] = "London"
  • you can also use the subscript syntax to change the value associated with the a particular key
airports["LHR"] = "Paris"
  • you can use the updateValue(_:forKey:) method to add or update the value of a particular key
  • the updateValue(_:forKey:) method returns the old value of an optional type of the dictionary’s value type
if let oldValue = airports.updateValue("Double Airport", forKey: "DOU") {
	print(oldValue)
}
  • you can use subscript syntax to retrieve a value from a dictionary for a particular key, and it returns an optional value of the dictionary’s value type, if the dictionary doesn’t contain the key, it returns nil
if let ariportName = airports["DOU"] {
	print(airportName)
} else {
	print("not found")
}
  • you can remove a key-value pair by assigning nil for that key
airports["APL"] = "Apple International"
airports["APL"] = nil
  • you can remove a key-value pair by calling the removeValue(forKey:) method. the method returns the removed value of an optional type, and if it doesn’t contain the key, it returns nil
if let airportName = airports.removeValue(forKey: "DOU") {
	print(airportName)
} else {
	print("not found")
}

Iterating Over A Dictionary

  • you can iterate a dictionary with a for-in loop, and each time it returns a tuple composed by a key and a value
for (airportCode, airportName) in airports {
	print("\(airportCode) : \(airportName)")
}
  • you can retrieve a dictionary’s values and keys by accessing its keys and values properties
for airportCode in ariports.keys {
	print("code: \(airportCode)")
} 
for airportName in airports.values {
	print("nae: \(airportName)")
}
  • you can initialize a new array with the keys and values properties
let airportCode = [String](airports.keys)
let airportName = [String](airports.values)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值