Swift集合类型-字典

2018-03-01  本文已影响15人  shaneYu

常用方法

// 这里不能使用let定义字典
var person = ["name": "jack", "age": "18"]

// 会将被删除的值返回,如果键不存在则返回nil
 let person1 = person.removeValue(forKey: "age")

// 还可以使用下标将对应的值设置为nil
person["name"] = nil
// 如果有值将返回更新之前的值
let oldAge = person.updateValue("33", forKey: "age")
 let person1 = ["name": "jack", "age": "18"]
 let person2 = ["name": "eric"]

// 合并
let person3 = person1.merging(person2) { (key1, key2) -> String in
            return key2
        }
// ["name": "eric", "age": "18"]
// 如果return key1,则结果为: ["name": "jack", "age": "18"]

// 简写
let person3 = person1.merging(person2) { $1 }

// 返回数组,数组内保存字典的value
let person = ["name": "jack", "age": "18"]
let dic0 = person.map { dic in
               return dic.value + "#"
        }
// ["jack#", "18#"]
// 返回字典,只对字典的value进行映射
let dic1 = person.mapValues { str in
            return str + "*"
        }
// ["name": "jack*", "age": "18*"]
let dic2 = person.filter { (dic) -> Bool in
            return dic.value.hasPrefix("j")
        }
// ["name": "jack"]
let dic3 = person.reduce("") { (result, dic) in
            return result + dic.value
        }
// jack18

字典在Swift4.0中更新的内容

// 新建一个Person结构体
struct Person {
    enum Gender {
        case male
        case female
    }

    var name: String
    var age: Int
    var gender: Gender
}
// persons
let p1 = Person(name: "jack", age: 18, gender: .male)
let p2 = Person(name: "eric", age: 11, gender: .male)
let p3 = Person(name: "helen", age: 13, gender: .female)

// person Array
let persons = [p1, p2, p3]

// group
let groups = Dictionary(grouping: persons) { person in
            return person.gender
        }

/* 结果为: [Person.Gender.male: [
            Person(name: "jack", age: 18, gender: Person.Gender.male), Person(name: "eric", age: 11, gender: Person.Gender.male)
            ],
         Person.Gender.female: [
            Person(name: "helen", age: 13, gender: Person.Gender.female)
            ]
        ] 
*/
// 与上面的mapValues使用方法一致
let groupsMap = groups.mapValues { persons in
            //return persons.first
            return persons.count
        }
// [Person.Gender.male: 2, Person.Gender.female: 1]
let person = ["name": "jack"]
// person["name"]: jack
// person["age"]: nil

// 指定默认值
// person["name", default: "ABC"] : jack
// person["age", default: "0"]: 0

所有更新的特性都在Swift官方文档博客中有说明。

上一篇下一篇

猜你喜欢

热点阅读