// ----- 数组 ----
let mutableAry = NSMutableArray.init()
var ary = ["1","2","3"]
// 1. 添加
mutableAry.addObjects(from: ary)
print("数组:",mutableAry)
// 2. 只有不可变数组才有 isEmpty
print(ary.isEmpty)
// 3. 用+=拼接数据
ary += ["4","5"]
print("数组+=:",ary)
// 4. 还可以利用下标来一次改变一系列数据值
// [注] 不可以用下标访问的形式去在数组尾部添加新项。
ary[1...3] = ["Bananas", "Apples" , "Store"]
print("数组替换:",ary)
// 5. 插入
ary.insert("FFFFFF", at: 0)
print("插入数据:" , ary)
// 6. 遍历
for name:String in ary {
print("遍历数据组:",name)
}
// 7. 删除
ary.remove(at: 5)
print("删除数组下标5的元素:",ary)
// --- 字典 ---
// 1. 字典初始化(1)
var dictionaryXjp = Dictionary<String,String>()
dictionaryXjp = ["name":"xjp","phone":"6666666666"]
print("字典初始化;",dictionaryXjp)
// 字典初始化(2)
var dicTwoInit = [Int:String]()
dicTwoInit = [2:"xjp",3:"fffff"]
print("第二种初始化方式:",dicTwoInit)
// 2. 增
var dictionAdd = [String:String]()
dictionAdd = ["name":"xjp","phone":"6666666666"]
dictionAdd["address"] = "dalian"
print("字典增:", dictionAdd)
print("字典查:",dictionAdd["name"] ?? "falseValue")
// 3. 遍历
let dict = ["name":"sunfusheng", "age":20, "blog":"sunfusheng.com"] as [String : Any]
//字典的遍历,使用for - in 循环来遍历字典中的键值对,每个字典中的数据项都以(key,value)元组的形式返回,可以使用临时常量或者变量来分解这些元组
for dictValure in dict {
print("字典遍历的结果:\(dictValure)")
}
/**
输出结果:
字典遍历的结果:(key: "name", value: "sunfusheng")
字典遍历的结果:(key: "age", value: 20)
字典遍历的结果:(key: "blog", value: "sunfusheng.com")
*/
//可以单独遍历出字典里的所有keys 或 values值
// (1)获取字典中所有的键
for dictKey in dict.keys {
print("dictKey = \(dictKey)")
}
for (airportCode, airportName) in dict {
print("元祖遍历 \(airportCode): \(airportName)")
}
/**
输出结果:
dictKey = name
dictKey = age
dictKey = blog
*/
// (2)获取字典中的所有值
for dictValue in dict.values {
print("dictValue = \(dictValue)")
}
/**
输出结果:
dictValue = sunfusheng
dictValue = 20
dictValue = sunfusheng.com
*/
//当只是需要使用某个字典的键集合或者值集合来作为某个接收Array 可以直接使用keys或者values属性构造一个新数组
let dictKeyArray = [String](dict.keys)
let dictValuesArray = [Any](dict.values)
print("dictKeyArray = \(dictKeyArray) \n dictValuesArray = \(dictValuesArray)")
/**
输出结果:
dictKeyArray = ["name", "age", "blog"]
dictValuesArray = ["sunfusheng", 20, "sunfusheng.com"]
*/
// 4. 删除
var deleDictionary = [String:String]()
deleDictionary = ["name":"xujianpeng","address":"heilongjiang","phone":"123123"]
// (1)可以使用下标语法来通过给某个键的对应值 赋值 为 “nil” 来从字典里 移除一个键值对
deleDictionary["name"] = nil
print("字典删除1:",deleDictionary)
// (2)
deleDictionary.removeValue(forKey: "address")
print("字典删除2:",deleDictionary)
// 删除全部: deleDictionary.removeAll()
// 5. 判断字典是否为空
let dicti = ["name":"sunfusheng", "age":20, "blog":"sunfusheng.com"] as [String : Any]
if dicti.isEmpty {
print("dict 字典为空")
} else {
print("dict 不为空 = \(dicti)")
}
let keys1 = dicti.keys.count
if keys1 == 0 {
print("dicti 字典为空")
} else {
print("dicti 不为空 = \(dicti)")
}