Swift 数组
数组初始化
基本语法:
[value 1, value2, value 3]
var shoppingList: String[] = ["Eggs","Milk"]
数组追加元素
append 函数追加 或通过+操作符
var shoppingList: String[] = ["Eggs", "Milk"]
hoppingList.append("Flour")
shoppingList += ["Chocolate Spread",
"Cheese","Butter"]
println("The shopping list contains
\(shoppingList.count) items.")
数组插入元素
使用 insert 方法
var shoppingList: String[] = ["Eggs", "Milk"]
shoppingList.insert("Maple Syrup", atIndex:
0)
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
数组删除元素
使用 removeAtIndex 方法
var shoppingList: String[] = ["Eggs", "Milk"]let mapleSyrup = shoppingList.removeAtIndex(0)
数组长度
使用 count 属性。
println("The shopping list contains
\(shoppingList.count)items.")
数组遍历
1.遍历方法1
var shoppingList: String[] = ["Eggs", "Milk"]
for item in shoppingList {
println(item)
}
2.遍历方法2有循环变量
var shoppingList: String[] = ["Eggs", "Milk"]
for (index, value) in enumerate(shoppingList) {
println("Item \(index + 1): \(value)")
}
Swift交流讨论论坛论坛:http://www.cocoagame.net
欢迎加入Swift技术交流群:362298485