跳到主要内容

Swift 列表

阐述

列表是同类元素的有序集合,类型是 [T]。支持的操作为

  • 创建
  • 连接
  • 索引
  • 更改
  • 遍历

实例

创建

创建时可以用字面值、构造函数或者两个列表相加:

var threeDoubles = Array(repeating: 0.0, count: 3)
var shoppingList = ["Eggs", "Milk"]
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]


var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

索引

索引可以用来读写:

var firstItem = shoppingList[0]
shoppingList[0] = "Six eggs"
shoppingList[4...6] = ["Bananas", "Apples"]

遍历

for item in shoppingList {
print(item)
}

for (index, value) in shoppingList.enumerated() {
print("Item \(index + 1): \(value)")
}

性质

相关内容

参考文献