数组
/* 创建数组 */
var arr = Array<String>()
var marr = [String]();
//创建字面量数组
var array : [String] = ["1","2","3","4"]
var array1 : Array<String> = ["1","2","3"]
//数组的数量
array.count
//数组判空
array.isEmpty
/* 增 */
array.append("5")
//增
array += ["6"]
array.insert("7", at: 3)
/* 删 */
array.removeLast()
array.removeFirst()
array.removeAll()
array.remove(at: 0)
/* 改 */
//修改第0个元素的值
array[0] = "modify"
//批量修改下标为1-3的元素的值
array[1...3] = ["a","b","c"]
/* 查 */
for value in array{
print(value)
}
//根据区间便利数组的元素
for value in array[0..<5]{
print(value)
}
//通过下标获取数组的元素
var arr = ["a","b","c"]
for i in 0..<arr.count{
print(i,arr[i])
}
//每个元素以及值的整数索引
for (index ,value) in array.enumerated(){
print(index,value)
}
集合
//创建集合
var set = Set<String>()
//字面量创建
var set1 : Set<String> = ["1" , "a", "2" , "b"]
//数量
set.count
//空判断
set.isEmpty
/*增*/
set.insert("3")
/* 删 */
//移除第一个元素
set.removeFirst()
//移除所有的元素
set.removeAll()
//已知集合中的元素,将其移除
set.remove("1")
//根据下表移除响应的元素
set.remove(at: set.startIndex)
set.remove(at: set.index(set.startIndex, offsetBy: 2))
/* 查 */
//输出无序的集合元素
for value in set {
print(value)
}
//输出排完序的集合元素
for value in set.sorted(){
print(value)
}
/*集合的交集和并集*/
var set1 : Set<String> = ["1","2","3","4"]
var set2 : Set<String> = ["3","4","5","6"]
//两个集合的交集
let result = set1.intersection(set2)
/* 输出结果是 "3", "4" */
//两个集合的并集
let result1 = set1.union(set2)
/* 输出结果是 "4", "2", "1", "5", "6", "3" */
字典
//创建字典
var dictionary = Dictionary<String,String>()
var dic1 : Dictionary<String,String> = ["1":"1","2":"2"]
var dic2 = ["3" : "3" ,"5" : "5"]
//字典中的键值对的数量
dic1.count
//字典中的所有的键
dic1.keys
//字典是否为空
dic1.isEmpty
/* 增 */
dic1["3"] = "3"
dic1["4"] = "4"
/* 删 */
dic1.removeAll()
dic1.removeValue(forKey: "4")
/* 改 */
dic1["4"] = "modify"
dic1.updateValue("newValue", forKey: "3")
/* 查 */
//便利所有的键值对
for value in dic1{
print(value)
}
//既有键又有值的便利方法
for (key ,value) in dic1{
print(key,value)
}
//便利所有的键的方法
for key in dic1.keys{
print(key)
}
//便利所有的值
网友评论