1.数组
定义一个数组
var shopList = ["橘子","香蕉","茄子"]
求数组里面元素的个数
var count = shopList.count
检查数组是否为空的一个属性 ,isEmpty属性
if shopList.isEmpty
{
print("数组为空")
}
else
{
print("数组不为空")
}
往数组末尾添加一个元素 。append 方法
shopList.append("辣椒")
在数组指定索引处插入元素
shopList.insert("猕猴桃", atIndex: 1)
print(shopList)
通过索引删除元素
shopList.removeAtIndex(2)
print(shopList)
数组的遍历,(迭代访问 for...in)
for 遍历 in shopList
{
print(遍历)
}
for index in 1...5{
print(index)
}
生成若干个重复元素组成的数组。
var threeDoubles = [Double](count :3,repeatedValue :2.5)
print(threeDoubles)
2.字典
定义一个字典, value设置成数组的时候取所有的key时,不能用dic.keys .而是要用 dic.allkeys.并且不能改变value。
var shopList = ["橘子","香蕉","茄子"]
var dic = ["name":shopList,"age":18,"sex":"男"]
print(dic)
取到所有的key ,value 如果没有集合的时候用keys。如果有用allkeys
var allkeys = Array(dic.allKeys)
print(allkeys)
取到所有的value
var allValues = Array (dic.allValues)
print(allValues)
3.显式定义 一个空的数组和字典
var emptyArr = [Int]()
emptyArr.insert(12, atIndex: 0)
print(emptyArr)
var emptyDic = [String:Double]()
emptyDic["age"] = 10
print(emptyDic)