数组是一个最常用的数据类型的应用程序。使用数组来组织你的应用程序的数据。具体地说,您可以使用数组类型来控制单个的元素类型,数组的元素类型。一个数组可以存储任何类型的元素从整数字符串类。迅速方便地创建数组在代码中使用一个数组文字:仅仅围绕方括号的逗号分隔的值列表。没有任何其他信息,迅速创建一个数组,包括指定的值,自动推断数组的元素类型。例如:
// An array of 'Int' elements
let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
// An array of 'String' elements
let streets = ["Albemarle", "Brandywine", "Chesapeake"]
您可以创建一个空数组通过指定数组的元素类型的声明。例如:
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
如果你需要一个数组与固定数量的preinitialized默认值,使用数组(重复计数:)初始值设定项。
var digitCounts = Array(repeating: 0, count: 10)
print(digitCounts)
// Prints "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]"
当您需要执行一个操作数组的所有元素,使用一个工党循环遍历该数组的内容。
for street in streets {
print("I don't live on \(street).")
}
使用isEmpty属性快速检查是否有任何元素的数组,或者使用count属性找到数组中元素的个数。
if oddNumbers.isEmpty {
print("I don't know any odd numbers.")
} else {
print("I know \(oddNumbers.count) odd numbers.")
}
网友评论