您的位置:首页 > 移动开发 > Swift

swift 学习计划(一)Array 数组、Dictionary 字典

2016-04-21 00:00 183 查看
摘要: Array 数组、Dictionary 字典

Swift 中的数组
· Array 数组
· 使用 [ ] 操作符声明数组

//数组
let myArray1 = []          //声明空数组

//let myArray2 = String[]() //这种方式会出现以下异常
//instance member 'subscript' cannot be used on type 'String'

var shoppingList = ["mac","ipad","iphone"]  //声明数组

//数组中的常用方法
print(shoppingList.count)       //数组的个数
print(shoppingList.capacity)    //数组的容量(容量的值>=count,并且是2的次方)
print(shoppingList.isEmpty)     //数组是否为空

//增加
shoppingList.append("ipod")     //给数组增加一个元素
print(shoppingList)             //输出这个数组的元素

shoppingList.insert("iMac", atIndex:2)  //插入一个元素,注意atIndex
print(shoppingList)        //输出插入元素后的新数组元素

//shoppingList += "a"
//在学习中看到,这种方式也是可以添加元素的,但是在我这里是会出现异常的,
//cannot convert value of type '[String]' to expected argument type 'inout String'

shoppingList += ["b","c"]  //再次增加两个元素
print(shoppingList)

//修改
print(shoppingList[1])     //输入list下标为1的值
shoppingList[1] = "ipad air"  //给list中下标为1的重新赋值
print(shoppingList[1])     //输出

shoppingList[2...4] = ["1","2","3"]  //把下标是2,3,4的元素替换成["1","2","3"]
print(shoppingList)

shoppingList[2...4] = ["1","2"]  //把下标是2,3,4的元素替换成["1","2"],这将意味着除了可以替换值以外,还可以改变数组的个数
print(shoppingList)

//删除
shoppingList.removeLast()  //移除最后一个元素
print(shoppingList)
shoppingList.removeAtIndex(2)  //移除下标为2的元素删除,在我这里应该是元素 1
print(shoppingList)
//shoppingList.removeAll()   //移除所有元素
print(shoppingList)

//数组的遍历1
for item in shoppingList{
print(item)
}

//数组的遍历2
//for (index, value) in enumerate(shoppingList){   //enumerate()这个方法是我学习过程中,看到的,用在这里出现了如下异常,
//'enumerate' is unvailable: call the 'enumerate()' method on the sequence
// 随后我使用EnumerateSequence()方法替换,虽然可以出效果,但是还是出现了如下警告。
//'init' is deprecated: it will be removed in Swift 3. Use the 'enumerate()' method...
//    print("Item\(index + 1):\(value)")
//}

Dictionary 字典
· 使用 [key : value] 操作符声明字典
//Dictionary 字典
//使用 [key : value] 操作符声明字典
let emptyDictionary = [:]   //声明一个空的字典
let emptyDictionary1 = Dictionary<String,Float>()  //声明一个空的字典,key为String类型,value为Float类型

var letter = ["A":"a","B":"b"]   //就是键值对
print(letter)

//添加、修改
letter ["A"] = "aa"    //查找原来的字典,如果包含这个key,那么就把这个字典对应的value进行替换。如果没有找到,即添加
print(letter)

letter ["C"] = "c"
print(letter)

//删除
letter["C"] = nil   //第一种方法
print(letter)

letter.removeValueForKey("B")   //第二种方法
print(letter)

//输出count
print("letter count is " + String(letter.count))
print("letter count is \(letter.count)")

//Dictionary 遍历
for (key , value) in letter{
print("\(key) : \(value)")
}

//遍历所有的key
for key in letter.keys{
print(key)
}

//遍历所有的value
for value in letter.values{
print(value)
}

let Allkeys = Array(letter.keys)   //把所有的key转换为数组
print(Allkeys)
let Allvalues = Array(letter.values)  //把所有的value转换为数组
print(Allvalues)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: