- 数组
- 增/删/改
- 合并
- 字典
- 定义
- 遍历
- 增/删/改
- 合并
一 数组
//OC中使用 [] 来定义数组, swift 一样,没有 @
//自动推导结果 [STring] ,表示数组中存放的都是 String
let arr = ["孙悟空", "唐僧", "猪八戒"]
print(arr)
// [Int] 表示存放的都是 int
//Swift中基本数据类型不需要包装
let arr2 = [1, 2, 3, 4, 5]
print(arr2)
//CG结构体
let p = CGPoint(x: 100, y: 200)
let arr3 = [p]
print(arr3)
// 混合数组在开发中几乎不用
//如果数组中类型不一致,会自动推导为 [NSObject]
// [AnyObject] 为任意类型
// swift 中的一个类可以没有父类
let arr4 = ["唐僧", 1, NSValue(cgPoint:p)] as [Any]
print(arr4)
let arr = ["孙悟空", "唐僧", "猪八戒"]
//1. 按下标遍历
print("~~~~~~下标遍历~~~~~~")
for i in 0..<arr.count {
print(arr[i])
}
//2. for in 遍历
print("~~~~~~for in 遍历~~~~~~")
for s in arr {
print(s)
}
//3. enum block 遍历,同时遍历下标和内容
print("~~~~~~enum block 遍历~~~~~~")
for e in arr.enumerated() {
print(e)
}
//4. 遍历下标和内容2
print("~~~~~~enum block 遍历2~~~~~~")
for (n, s) in arr.enumerated() {
print("\(n), \(s)")
}
//5. 反序遍历
print("~~~~~~反序遍历~~~~~~")
for c in arr.reversed() {
print(c)
}
//6.反序遍历下标和内容
print("~~~~~~反序遍历下标和内容~~~~~~")
for (n, s) in arr.enumerated().reversed() {
print("\(n) \(s)")
}
//OC 中数组可变 NSMutableArray, 不可变 NSArray, Swift 中可变(var) ,不可变(let)
var arr = ["孙悟空", "唐僧", "猪八戒"]
// 添加元素
arr.append("沙僧")
print(arr)
//修改
//通过下标,不能越界
arr[3] = "德华"
print(arr)
//删除
arr.remove(at: 2)
print(arr)
//删除全部,并且保留空间
arr.removeAll(keepingCapacity:true)
print("\(arr) , \(arr.capacity)")
//数组合并
var arr1 = ["孙悟空", "唐僧", "猪八戒"] as [Any]
let arr2 = ["德华", 80] as [Any]
//要合并,类型必须一致
arr1 += arr2
print(arr1)
二 字典
// 定义
//OC中用的是 {} , Swift 中用的是 []
let dict = ["name":"唐僧", "age":90] as [String : Any]
print(dict)
let arr = [
["name":"唐僧", "age":90],
["name":"沙僧", "age":9]
]
print(arr)
var dict = ["name":"唐僧", "age":90] as [String : Any]
//新增, 如果KEY 不存在,就是新增
dict["title"] = "吃肉"
print(dict)
//修改 , 通过KEY 取值,修改
//如果KEY 存在, 就是修改
dict["name"] = "沙僧"
print(dict)
// 删除
dict.removeValue(forKey: "name")
print(dict)
//遍历
let dict = ["name":"唐僧", "age":90, "title":"大哥"] as [String : Any]
for e in dict {
print(e)
}
for (n,s) in dict {
print("\(n) \(s)")
}
//合并
var dict1 = ["name":"唐僧", "age":90, "title":"大哥"] as [String : Any]
let dict2 = ["name":"唐僧", "height":90] as [String : Any]
for e in dict2 {
dict1[e.key] = dict2[e.key]
}
print(dict1)