美文网首页
Swift 2 学习笔记 7.字典和集合

Swift 2 学习笔记 7.字典和集合

作者: Maserati丶 | 来源:发表于2018-11-18 21:58 被阅读0次

课程来自慕课网liuyubobobo老师


字典:存储 键-值 数据对的无序数据集
  • 字典的初始化
var dict = ["Swift":"雨燕","python":"大蟒","java":"爪哇岛"]
var emptyDictonary1: [String : Int] = [:]
var emptyDictonary2: Dictionary<String,Int> = [:]
var emptyDictonary3 = [String : Int]()
var emptyDictonary4 = Dictionary<String,Int>()
for (key,value) in dict {
    print("\(key):\(value)")
}
  • 字典的操作
var user = ["name":"liuyubo","password":"bobobo","occupation":"programmer"]
user["occupation"] = "freelancer"  // key存在则更新
user.updateValue("imooc", forKey: "password")  // key存在则更新(返回修改之前的值)
user["email"] = "imooc@qq.com"  // key不存在则新增
user.updateValue("imooc.com", forKey: "website")  // key不存在则新增(返回nil)
user["email"] = nil  //删除
user.removeValue(forKey: "website")  //删除(返回删除前的值)
user.removeAll()  //清空字典
集合:一个无序的无重复的数据集
  • 集合的初始化
var skillOfA: Set<String> = ["Swift","OC","OC"]  // {"OC","Swift"}
skillOfA.count  // 2
var emptySet1: Set<String> = []
var emptySet2 = Set<String>()
var skillOfB: Set = ["HTML","CSS","Javascript"]
  • 集合的基本用法
var skillOfA: Set<String> = ["Swift","OC"]
var skillOfB: Set = ["HTML","CSS","Javascript"]
var skillOfC: Set<String> = []
skillOfC.insert("Swift")
skillOfC.remove("Swift")
skillOfC.remove("CSS")
skillOfC.removeAll()
  • 集合的更多用法 -> Swift4
var skillOfA: Set<String> = ["Swift","OC"]
var skillOfB: Set<String> = ["HTML","CSS","Javascript"]
var skillOfC: Set<String> = ["Swift","HTML","CSS"]
// 并集
skillOfA.union(skillOfC)  // {"OC","CSS","Swift","HTML"}
// 交集
skillOfA.intersection(skillOfC)  // {"Swift"}
// 减法(两个集合当中不包含某个合集值的新集合)
skillOfA.subtracting(skillOfC)  // {"OC"}
// 异或(只包含两个合集各自有的非共有值的新合集)
skillOfA.symmetricDifference(skillOfC)  // {"OC","HTML","CSS"}

var skillOfD: Set<String> = ["OC"]
// 子集
skillOfD.isSubset(of: skillOfA)  // true
// 真子集
skillOfD.isStrictSubset(of: skillOfA)  // true
// 超集
skillOfA.isSuperset(of: skillOfD)  // true
// 真超集 
skillOfA.isStrictSuperset(of: skillOfD)  // true
// 相离(没有公共元素)
skillOfA.isDisjoint(with: skillOfB)  // true
  • 选择合适的数据结构
    数组:有序
    字典:键-值数据对
    集合:无序、唯一、提供集合操作、快速查找

相关文章

网友评论

      本文标题:Swift 2 学习笔记 7.字典和集合

      本文链接:https://www.haomeiwen.com/subject/zirnfqtx.html