【swift】Introduction of swift collections

364 阅读1分钟

这是我参与 8 月更文挑战的第 7 天,活动详情查看: 8月更文挑战

Swift 公布了Collections和Algorithms的开源库。

目前公布的Collections类,包括三个主要的数据结构: deque、ordered set 和 ordered dictionary。

Deque

  • 双向队列

  • 有序的、随机访问的、可修改的的集合类型

var colors: Deque = ["red", "yellow", "blue"]
print(colors) // [red, yellow, blue]

colors.prepend("orange") // 在双向队列前面添加元素
colors.append("green") // 在双向队列后面添加元素
print(colors) // [orange, red, yellow, blue, green]

print(colors[1])
colors[1] = "peach"
print(colors)
colors.insert(contentsOf: ["violet", "pink"], at: 1)
print(colors)
colors.remove(at: 2)
print(colors)
colors.sort()
print(colors)

为此 swift 还做了与使用Array和c++中的deque中进行predepend和随机访问的性能对比

OrderedSet

  • 顺序集合

  • OrderedSet 使用标准的数据结构来作为元素的存储。

let buildingMaterials: OrderedSet = ["straw", "sticks", "bricks"]

for i in 0..< buildingMaterials {
    print("Little piggie #\(i) build a house of \(buildingMaterials[i])")
}

buildingMaterials.append("straw") // (inserted: false, index: 0)
buildingMaterials.contains("glass") // false
buildingMaterials.append("glass") // (inserted: true, index: 3)

func buildHouses(_ houses: Array<String>)

buildHouses(buildingMaterials) // error
buildHouses(buildingMaterials.elements) // OK

OrderedDictionary

  • 有序字典
let responses: OrderedDictionary = [
    200: "OK",
    403: "Forbidden",
    404: "Not Found"
]

responses[200]
responses[500] = "Internal Server Error"

for (code, phrase) in responses {
  print("(code) ((phrase))")
}
// 200 (OK)
// 403 (Forbidden)
// 404 (Not Found)
// 500 (Internal Server Error)

if let i = responses.index(forKey: 404) {
  responses.keys[i] // 404
  responses.values[i] // "Not Found"
  responses.remove(at: i + 1) // (500, "Internal Server Error")
}
// `responses` is now [200: "OK", 403: "Forbidden", 404: "Not Found"]