Swift基础 - Dictionary及高阶函数

109 阅读2分钟

本文章内容基于Swift5。

初始化

// 创建一个空字典
let someDic = [String: Int]()
let someDic2: [String: Int] = [:]

// 给定值创建字典
let someDic3 = ["A": 1, "B": 2, "C": 3]

// 基于序列的初始化
let keys = ["keyA", "keyB", "keyC"]
let values = [10, 20, 30]
let dict = Dictionary(uniqueKeysWithValues: zip(keys, values))
print("dict: \(dict)")   // ["keyA": 10, "keyB": 20, "keyC": 30]

字典过滤

let dict2 = ["A": 10, "B": 20, "C": 30, "D": 40]
let dict3 = dict2.filter { $0.value > 20 }
print(dict3)     // ["D": 40, "C": 30]

字典分组

let cities = ["Beijing", "GuiYang", "Baoshan", "AnShun", "ChangDe", "GuangZhou"]

// 根据首字母对字典的值进行分组
let groupDict = Dictionary(grouping: cities) { $0.first! }
print(groupDict)     

["A": ["AnShun"], 
 "C": ["ChangDe"], 
 "B": ["Beijing", "Baoshan"], 
 "G": ["GuiYang", "GuangZhou"]
 ]

增删改查

访问
let dict4 = [1: "One", 2: "Two", 3: "Three"]
let value41 = dict4[1]     // One
添加、修改
var dict5 = [1: "One", 2: "Two", 3: "Three"]

// 修改
let value51 = dict5.updateValue("Two_2", forKey: 2)
print(dict5)   // [2: "Two_2", 3: "Three", 1: "One"]

// 修改
dict5[1] = "One_1"
print(dict5)   // [1: "One_1", 3: "Three", 2: "Two_2"]

// 添加
dict5[4] = "Four"
print(dict5)   // [2: "Two_2", 3: "Three", 4: "Four", 1: "One_1"]
删除
var dict6 = [1: "One", 2: "Two", 3: "Three"]

// 使用 removeValueForKey()删除键值对,如果存在并返回已删除的值,不存在值,则返回nil
let dict7 = dict6.removeValue(forKey: 5)

// 使用下标语法从字典中删除键值对,方法是为该键分配值 nil
dict6[2] = nil
print(dict6)        // [1: "One", 3: "Three"]

遍历字典

  1. 使用 for-in 循环遍历字典中的整个键值对
var dict8 = [1: "One", 2: "Two", 3: "Three"]
for (key, value) in dict8 {
    print("key: \(key), value:\(value)")
}
//key: 1, value:One
//key: 2, value:Two
//key: 3, value:Three
  1. 使用 enumerate()函数,该函数返回项目的索引及其(键、值)对
for (index, value) in dict8.enumerated() {
    print("index: \(index), value:\(value)")
}
//index: 0, value:(key: 1, value: "One")
//index: 1, value:(key: 2, value: "Two")
//index: 2, value:(key: 3, value: "Three")
  1. 只获取键
for key in dict8.keys {
    print("key: \(key)")
}
//key: 2
//key: 3
//key: 1
  1. 只获取值
for value in dict8.values {
    print("value: \(value)")
}
//value: One
//value: Two
//value: Three

函数使用

dictionary 转为 元组
var dict9 = [1: "One", 2: "Two", 3: "Three"]
let result = dict9.map { key, value in
    return (key, value)
}
print("\(result)")   // [(3, "Three"), (2, "Two"), (1, "One")]
key 或 value 是否包含某个值
var dict10 = [1: "One", 2: "Two", 3: "Three"]
let hasKey = dict10.keys.contains(2)
let hasValue = dict10.values.contains("One1")
使用merge进行合并键值对
var dict11 = [1: "One", 2: "Two", 3: "Three"]
let dict12 = [1: "OneNew"]

// 合并策略 $1,使用dict12值覆盖
dict11.merge(dict12, uniquingKeysWith: { $1 })

print(dict11)    // [2: "Two", 3: "Three", 1: "OneNew"]
使用mapValues,保持字典结构,只对其中的值进行变换
enum Setting {
    case text(String)
    case int(Int)
    case bool(Bool)
}

let dict13: [String: Setting] = [
    "Name": .text("Xiao ming"),
    "Age": .int(20),
    "Graduate": .bool(false)
]

let dict14 = dict13.mapValues { value -> String in
    // 对value进行转换
    switch value {
    case let .text(text): return text
    case let .int(number): return String(number)
    case let .bool(value): return String(value)
    }
}

print("New: \(dict14)")     // ["Graduate": "false", "Name": "Xiao ming", "Age": "20"]