听说Swift很NB,那么来勉强学点(3.1)--集合类型数组

数组,是有序数据的集合,存储的数据值类型必须要明确。 

创建一个空数组 

var someInts = [Int]()
someInts.append(3)
someInts = []
创建一个带默认值得数组

var threeDoubles = [Double](count:3, repeatedValue:2.5)
//等价于
var threeDoubles:[Double] = [2.5,2.5,2.5]
可以使用加法操作符 + 来组合两种已存在的相同类型数组,新数组的数据类型会被从两个数组的数据类型中推断出来。

var anotherThreeDoubles = Array(count:3, repeatedValue:2.5)
var sixDoubles = threeDoubles + anotherThreeDoubles
用字面量构造数组 

var shoppingList:[String] = ["Eggs","Milk"]
//根据Swift的类型推断机制,上边的初始化可以等价于
var shoppingList = ["Eggs","Milk"]
访问和修改数组 
使用布尔值属性isEmpty作为检查count属性的值是否为0 

if shoppingList.isEmpty {
    print("The shopping list is empty")
}else{
    print("The shopping list is not empty")
}
可以使用append(_:)方法在数组后面添加新的数据项 

shoppingList.append("Flour")
使用加法赋值运算符(+=)也可以直接在数组后面添加一个或多个拥有相同类型的数据项 

shoppingList += ["Baking Powder"]
shoppingList += ["Chocolate Spread","Cheese","Butter"]
可以直接使用下标语法来获取数组中的数据项 

var firstItem = shoppingList[0]
也可以用下标来改变某个已有索引值对应的数据值 

shoppingList[0] = "Six eggs"
还可以用下标来一次改变一系列数据值 

shoppingList[4...6] = ["Bananas","Apples"]
为数组插入某个值 

shoppingList.insert("Maple Syrup",atIndex:0)
删除数组的某个值,返回被移除的值 

var removeValue = shoppingList.removeAtIndex(0)
数组的遍历 

//对数组中的值进行遍历
for item in shoppingList{
    print(item)
}
//对数组中的索引与值一同遍历
for (index,value) in shoppingList.enumerate(){
    print("Item \(String(index + 1)):\(value)")
}















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值