Swift 字典用来存储无序的相同类型数据的集合,Swift 字典会强制检测元素的类型,如果类型不同则会报错。
Swift 字典每个值(value)都关联唯一的键(key),键作为字典中的这个值数据的标识符。
和数组中的数据项不同,字典中的数据项并没有具体顺序。
Swift 字典的key没有类型限制可以是整型或字符串,但必须是唯一的。
如果创建一个字典,并赋值给一个变量,则创建的字典就是可以修改的。这意味着在创建字典后,可以通过添加、删除、修改的方式改变字典里的项目。如果将一个字典赋值给常量,字典就不可修改,并且字典的大小和内容都不可以修改。
一、创建字典
- 1、使用以下语法来创建一个特定类型的空字典:
var someDict = [KeyType: ValueType]()
- 2、字典的初始化
let dict01 = Dictionary<Int, String>()
let dict02 = [Int: String]()
let dict03: Dictionary<Int, String> = [:]
let dict04: [Int: String] = [:]
二、字典操作
1、访问字典
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
print( "key = 1 的值为 \(someDict[1])" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )
输出:
key = 1 的值为 Optional("One")
key = 2 的值为 Optional("Two")
key = 3 的值为 Optional("Three")
2、修改和添加字典
var someDict:[Int:String] = [1:"1", 2:"Two", 3:"Three"]
someDict.updateValue("One", forKey: 1)
print(someDict)
someDict.updateValue("Five", forKey: 4)
print(someDict)
someDict[4] = "Four"
someDict[5] = "Five"
print(someDict)
输出:
[2: "Two", 3: "Three", 1: "One"]
[2: "Two", 3: "Three", 1: "One", 4: "Five"]
[5: "Five", 2: "Two", 3: "Three", 1: "One", 4: "Four"]
3、移除 Key-Value 对
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
someDict.removeValue(forKey: 3)
print(someDict)
someDict[2] = nil
print(someDict)
输出:
[2: "Two", 1: "One"]
[1: "One"]
4、遍历字典
let someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict {
print("\(key) - \(value)")
}
for (key, value) in someDict.enumerated() {
print("\(key) - \(value)")
}
输出:
2 - Two
3 - Three
1 - One
0 - (key: 2, value: "Two")
1 - (key: 3, value: "Three")
2 - (key: 1, value: "One")
5、count 属性
let someDict1: [Int: String] = [1: "One", 2: "Two", 3: "Three"]
let someDict2: [Int: String] = [4: "Four", 5: "Five"]
print("someDict1 含有 \(someDict1.count) 个键值对")
print("someDict2 含有 \(someDict2.count) 个键值对")
输出:
someDict1 含有 3 个键值对
someDict2 含有 2 个键值对
6、isEmpty 属性
let someDict1: [Int: String] = [1: "One", 2: "Two", 3: "Three"]
let someDict2: [Int: String] = [4: "Four", 5: "Five"]
let someDict3: [Int: String] = [Int: String]()
print("someDict1 = \(someDict1.isEmpty)")
print("someDict2 = \(someDict2.isEmpty)")
print("someDict3 = \(someDict3.isEmpty)")
输出:
someDict1 = false
someDict2 = false
someDict3 = true
三、转换
1、字典转换为数组
let someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
let dictKeys = [Int](someDict.keys)
let dictValues = [String](someDict.values)
print("输出字典的键(key)")
for (key) in dictKeys {
print("\(key)")
}
print("输出字典的值(value)")
for (value) in dictValues {
print("\(value)")
}
输出:
输出字典的键(key)
2
3
1
输出字典的值(value)
Two
Three
One