https://github.com/Zhangjingwang1993/Swift.git
Swift 语言提供Arrays
、Sets
和Dictionaries
三种基本的集合类型用来存储集合数据。数组(Arrays)是有序数据的集。集合(Sets)是无序无重复数据的集。字典(Dictionaries)是无序的键值对的集
可变数组
var someInts = [Int]() // 空数组
var genders1:[String] = ["boy","girl"];// 字符数组
var numbers = [1,2,3,4,5] // 整型数组
不可变数组
let genders = ["male","female"]
数组元素的个数和访问数组元素
print("numbers 数组的长度: \(numbers.count) 数组的第一个值:\(numbers[0])")
追加数组元素
numbers.append(6)
print("numbers 数组的长度: \(numbers.count) 数组的第一个值:\(numbers[5])")// 6 6
// 使用加法赋值运算符(+=) 也可以在数组后面添加数组
genders1+=["ios"]
print("numbers 数组:\(genders1)") // 运行结果 : numbers 数组:["boy","girl","ios"]
在某个位置插入元素,Swift 点语法
genders1.insert("Objective-C",atIndex: 2)
print("numbers 数组:\(genders1)") // 运行结果 : numbers 数组:["boy","girl","Objective-C","ios"]
删除元素
genders1.removeAtIndex(2)
print("numbers 数组:\(genders1)") // 运行结果 : numbers 数组:["boy","ios"]
判断数组是否为空
if genders1.isEmpty{
print("null")
}
遍历数组
for begin in genders1{
print(begin)
}
// 或者
for (index,value) in genders1.enumerate(){
print("Item \(String(index + 1)): \(value)")
}
字典的定义
var dic = ["ios":"swfit","coder":"I"]
字典访问 键对应的值
let name = dic["ios"]
print(name) // Optional("swfit")
添加
dic ["boy"] = "Zhang"
print(dic) // ["boy": "Zhang","coder": "I","ios": "swfit"]
删除
dic.removeValueForKey("boy")
print(dic) // ["coder": "I","ios": "swfit"]
修改
dic.updateValue("Student",forKey: "coder")
print(dic) // ["coder": "Student","ios": "swfit"]
遍历字典
for (key,value) in dic{
print("key:\(key) value:\(value)")
}
//或者
for d in dic{
print("key1:\(d.0) value1:\(d.1)")
}
单独遍历key 和 value
for key in dic.keys{
print("Key= \(key)")
}
for value in dic.values{
print("value= \(value)")
}