objective-c与swift字典的简单使用
分类: NSDictionary (NSDictionaryCreation)
在objective-c中字典的简单使用:
// 建立一个空字典
+ (instancetype)dictionary;
// 例子
NSDictionary * dic = [NSDictionary dictionary];
// 简写形式
NSDictionary * dic = @{};
// 建立一个拥有单个键值对字典
+ (instancetype)dictionaryWithObject:(id)object forKey:(id <NSCopying>)key;
// 实例
NSDictionary * dic = [NSDictionary dictionaryWithObject:@"OC" forKey:@"OCKey"];
// 简写
NSDictionary * dic = @{@"OC":@"OCKey"};
// 建立一个拥有多个键值对的字典
+ (instancetype)dictionaryWithObjectsAndKeys:(id)firstObject, ... NS_REQUIRES_NIL_TERMINATION;
// 实例
NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"OC",@"OCKey",@"张三",@"name", nil];
// 简写
NSDictionary * dic = @{@"OC":@"OCKey",@"张三":@"name"};
以上的例子均为不可变字典,数组所储存的键值对的值为对象,键位字符串的标识,字典一旦决定键值对个数不可添加或删除.
根据键也就是Key来取值.
在swift中字典的简单使用:
// 实例化一个空字典
NSDictionary();
// 简写
var dic:NSDictionary = [:];
// 建立一个拥有一个键值对的字典
convenience init(object: AnyObject, forKey key: NSCopying)
// 例子
var dic:NSDictionary = NSDictionary(object: "OC", forKey: "OCKey");
// 简写
var dic:NSDictionary = ["swiftKey":"swift"];
/** 2015,12,22修改 废弃 */
convenience init(objectsAndKeys objects: AnyObject...)
// 建立一个拥有多个键值对的字典
public convenience init(objects: [AnyObject], forKeys keys: [NSCopying])
/** 2015,12,22修改 废弃 */
var dic = NSDictionary(objectsAndKeys: "OC","OCKey","张三","name")
// 例子
var dic = NSDictionary(objects: ["张三","OC"], forKeys: ["name","OCKey"]);
// 简写
var dic = [ "name":"张三","age":"18","id":"1" ];
// 指定字典中的参数
var dic:Dictionary = Dictionary<NSString ,Float>();
在swift中与OC还是有些变化首先简写形式由 @{}
变化为 [:]
其次,在使用swift的便利构造器时,左边是值,而右边是key, 在简写形式中,则变化为左边是key右边是值.