Skip to content

Swift Array API

Swift 的 Dictionary<K, V> —— 一种将唯一键映射到值的集合,平均查找时间为 O(1)。

1 class · 8 methods

Dictionary

8 methods

一种元素为键值对的集合。桥接到 NSDictionary 的值类型。

Array.append(_ newElement: Element)

访问与给定键关联的值,如果键不存在则返回 nil。

Parameters

NameTypeDescription
newElementElementElement 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)  // 3
Array.remove(at: Int) -> Element

仅包含字典键的集合。

Parameters

NameTypeDescription
atIntIndex 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

NameTypeDescription
elementElementElement to search for.

Returns

Bool

Example

swift
let nums = [1, 2, 3]
print(nums.contains(2))  // true
print(nums.contains(9))  // false
Array.map<T>(_ transform: (Element) throws -> T) rethrows -> [T]

更新给定键对应的值,返回旧值(如果键是新的则返回 nil)。

Parameters

NameTypeDescription
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

NameTypeDescription
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

NameTypeDescription
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) -> String

Returns a string containing the elements of the sequence, separated by the given separator.

Parameters

NameTypeDescription
separatorStringSeparator between elements.

Returns

String

Example

swift
let parts = ["a", "b", "c"]
let s = parts.joined(separator: "-")
// s == "a-b-c"