下面表格列出了数组的常用方法:
创建一个空数组
var someInts = [Int]() print("someInts is of type [Int] with \(someInts.count) items.") // 打印 "someInts is of type [Int] with 0 items."
someInts.append(3) // someInts 现在包含一个 Int 值 someInts = [] // someInts 现在是空数组,但是仍然是 [Int] 类型的。
创建一个带默认值的数组
var threeDoubles = [Double](count: 3, repeatedValue:0.0) // threeDoubles 是一种 [Double] 数组,等价于 [0.0, 0.0, 0.0]
通过两个数组相加创建一个数组
var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5) // anotherThreeDoubles 被推断为 [Double],等价于 [2.5, 2.5, 2.5] var sixDoubles = threeDoubles + anotherThreeDoubles // sixDoubles 被推断为 [Double],等价于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
访问和修改数组
var shoppingList = ["Eggs", "Milk"] print("The shopping list contains \(shoppingList.count) items.") // 输出 "The shopping list contains 2 items."(这个数组有2个项)
使用布尔值属性isEmpty作为检查count属性的值是否为 0
if shoppingList.isEmpty { print("The shopping list is empty.") } else { print("The shopping list is not empty.") } // 打印 "The shopping list is not empty.
使用append(_:)方法在数组后面添加新的数据项:
shoppingList.append("Flour") // shoppingList 现在有3个数据项
使用加法赋值运算符(+=)也可以直接在数组后面添加一个或多个拥有相同类型的数据项:
shoppingList += ["Baking Powder"] // shoppingList 现在有四项了 shoppingList += ["Chocolate Spread", "Cheese", "Butter"] // shoppingList 现在有七项了
可以直接使用下标语法来获取数组中的数据项
var firstItem = shoppingList[0] // 第一项是 "Eggs"
也可以用下标来改变某个已有索引值对应的数据值:
shoppingList[0] = "Six eggs" // 其中的第一项现在是 "Six eggs" 而不是 "Eggs"
利用下标来一次改变一系列数据值
shoppingList[4...6] = ["Bananas", "Apples"] // shoppingList 现在有6项
调用数组的insert(_:atIndex:)方法来在某个具体索引值之前添加数据项:
shoppingList.insert("Maple Syrup", atIndex: 0) // shoppingList 现在有7项
可以使用removeAtIndex(_:)方法来移除数组中的某一项
let mapleSyrup = shoppingList.removeAtIndex(0)
想把数组中的最后一项移除,可以使用removeLast()方法
let apples = shoppingList.removeLast()
数组的遍历
for item in shoppingList { print(item) }
如果我们同时需要每个数据项的值和索引值,可以使用enumerate()方法来进行数组遍历
for (index, value) in shoppingList.enumerate() { print("Item \(String(index + 1)): \(value)") } // Item 1: Six eggs // Item 2: Milk // Item 3: Flour // Item 4: Baking Powder // Item 5: Bananas
数组排序
vararray = [1,4,2,8,3,3,10,9] letsortedArray = array.sort(<) print(sortedArray) array.sortInPlace(>) print("原数组排序:", array)
oc addObjectsFromArray 在swift中应用
var array = [1,2,3,4,5] let array1 = [6,7,8,9,10] array += array1 print(array);