- Swift 字典的
key没有类型限制可以是整型或字符串,但必须是唯一的。
- 创建一个字典,并赋值给一个变量,则创建的字典就是可以修改的。这意味着在创建字典后,可以通过添加、删除、修改的方式改变字典里的项目。
- 将一个字典赋值给常量,字典就不可修改,并且字典的大小和内容都不可以修改。
一.字典的用法
1.1 创建字典
var dict = [Int: String]()
var dict : [Int:String] = [1:"One", 2:"Two", 3:"Three"]
1.2 访问字典
var dict : [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")
*/
1.3 修改字典
- 如果存在则修改
key 对应的值。
- 如果
key 不存在,则添加值。
1.3.1 通过指定的 key 来修改字典的值
var dict : [Int:String] = [1:"One", 2:"Two", 3:"Three"];
dict[4] = "四";
print(dict[4]);
//Optional("四")
var dict : [Int:String] = [1:"One", 2:"Two", 3:"Three"];
dict[1] = "一";
print(dict[1]);
//Optional("一")
1.3.2 使用 updateValue(forKey:) 方法
updateValue(_:forKey:) 方法返回旧的 Optional 值。
var dict : [Int:String] = [1:"One", 2:"Two", 3:"Three"];
let oldKV = dict.updateValue("一", forKey: 1);
print( "key = 1 的旧值为 \(oldKV)");
print( "key = 1 的新值为 \(dict[1])");
/*
key = 1 的旧值为 Optional("One")
key = 1 的新值为 Optional("一")
*/
var dict : [Int:String] = [1:"One", 2:"Two", 3:"Three"];
let oldKV = dict.updateValue("四", forKey: 4);
print( "key = 4 的旧值为 \(oldKV)");
print( "key = 4 的新值为 \(dict[4])");
/*
key = 4 的旧值为 nil
key = 4 的新值为 Optional("四")
*/
1.4 移除 Key-Value 对
1.4.1 指定键的值为 nil 来移除 key-value
var dict : [Int:String] = [1:"One", 2:"Two", 3:"Three"];
dict[1] = nil;
print(dict);
//[2: "Two", 3: "Three"]
1.4.2 使用 removeValueForKey() 方法
var dict : [Int:String] = [1:"One", 2:"Two", 3:"Three"];
dict.removeValue(forKey: 1);
print(dict);
//[2: "Two", 3: "Three"]
1.5 遍历字典
var dict : [Int:String] = [1:"One", 2:"Two", 3:"Three"];
for (key, value) in dict {
print("key: \(key) - value: \(value)");
}
/*
key: 1 - value: One
key: 2 - value: Two
key: 3 - value: Three
*/
1.6 字典转换为数组
var dict : [Int:String] = [1:"One", 2:"Two", 3:"Three"];
let dictKeys = [Int](dict.keys)
let dictValues = [String](dict.values)
print("输出字典的键(key)")
for (key) in dictKeys {
print("\(key)")
}
print("输出字典的值(value)")
for (value) in dictValues {
print("\(value)")
}
/*
输出字典的键(key)
1 3 2
输出字典的值(value)
One Three Two
*/
1.7 count 属性
var dict : [Int:String] = [1:"One", 2:"Two", 3:"Three"];
print(dict.count);
//3
1.8 isEmpty 属性
var dict1 : [Int:String] = [1:"One", 2:"Two", 3:"Three"];
var dict2 = [Int:String]();
print(dict1.isEmpty); //false
print(dict2.isEmpty); //true