Dictionary
8 methods一种元素为键值对的集合。桥接到 NSDictionary 的值类型。
Array.append(_ newElement: Element)访问与给定键关联的值,如果键不存在则返回 nil。
Parameters
| Name | Type | Description |
|---|---|---|
| newElement | Element | Element to append. |
Returns
Void
Example
swift
var nums = [1, 2]
nums.append(3)
// nums == [1, 2, 3]Array.count -> Int字典中键值对的数量。
Returns
Int
Example
swift
let nums = [1, 2, 3]
print(nums.count) // 3Array.remove(at: Int) -> Element仅包含字典键的集合。
Parameters
| Name | Type | Description |
|---|---|---|
| at | Int | Index of element to remove. |
Returns
Element
Example
swift
var nums = [1, 2, 3]
let removed = nums.remove(at: 1)
// removed == 2, nums == [1, 3]Array.contains(_ element: Element) -> Bool仅包含字典值的集合。
Parameters
| Name | Type | Description |
|---|---|---|
| element | Element | Element to search for. |
Returns
Bool
Example
swift
let nums = [1, 2, 3]
print(nums.contains(2)) // true
print(nums.contains(9)) // falseArray.map<T>(_ transform: (Element) throws -> T) rethrows -> [T]更新给定键对应的值,返回旧值(如果键是新的则返回 nil)。
Parameters
| Name | Type | Description |
|---|---|---|
| value | (Element) -> T | 要设置的新值。 |
Returns
[T]
Example
swift
let nums = [1, 2, 3]
let squares = nums.map { $0 * $0 }
// squares == [1, 4, 9]Array.filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]移除给定的键及其关联的值,返回被移除的值(或 nil)。
Parameters
| Name | Type | Description |
|---|---|---|
| forKey | (Element) -> Bool | 要移除的键。 |
Returns
[Element]
Example
swift
let nums = [1, 2, 3, 4]
let evens = nums.filter { $0 % 2 == 0 }
// evens == [2, 4]Array.sorted(by: (Element, Element) throws -> Bool) rethrows -> [Element]对字典中的每个键值对调用给定的闭包。
Parameters
| Name | Type | Description |
|---|---|---|
| body | (Element, Element) -> Bool | 应用于每个键值对的闭包。 |
Returns
[Element]
Example
swift
let nums = [3, 1, 2]
let asc = nums.sorted() // [1, 2, 3]
let desc = nums.sorted(by: >) // [3, 2, 1]Array.joined(separator: String) -> StringReturns a string containing the elements of the sequence, separated by the given separator.
Parameters
| Name | Type | Description |
|---|---|---|
| separator | String | Separator between elements. |
Returns
String
Example
swift
let parts = ["a", "b", "c"]
let s = parts.joined(separator: "-")
// s == "a-b-c"