尝试用swift字典中的键字符串填充数组。
var componentArray: [String]
let dict = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Components", ofType: "plist")!)
componentArray = dict.allKeys
这将返回一个错误:'AnyObject'与string不相同
也试过
componentArray = dict.allKeys as String
but get: 'String'不能转换为[String]
NSDictionary是类(通过引用传递)
字典是结构(按值传递)
======数组从NSDictionary ======
NSDictionary有allKeys和allValues获取属性
类型(任何)。
let objesctNSDictionary =
NSDictionary.init(dictionary: ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"])
let objectArrayOfAllKeys:Array = objesctNSDictionary.allKeys
let objectArrayOfAllValues:Array = objesctNSDictionary.allValues
print(objectArrayOfAllKeys)
print(objectArrayOfAllValues)
======数组从字典======
字典的键和值属性的Apple引用。
let objectDictionary:Dictionary =
["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
let objectArrayOfAllKeys:Array = Array(objectDictionary.keys)
let objectArrayOfAllValues:Array = Array(objectDictionary.values)
print(objectArrayOfAllKeys)
print(objectArrayOfAllValues)
这个答案将用于swift字典w/ String键。就像下面这个。
let dict: [String: Int] = ["hey": 1, "yo": 2, "sup": 3, "hello": 4, "whassup": 5]
这是我将使用的扩展。
extension Dictionary {
func allKeys() -> [String] {
guard self.keys.first is String else {
debugPrint("This function will not return other hashable types. (Only strings)")
return []
}
return self.flatMap { (anEntry) -> String? in
guard let temp = anEntry.key as? String else { return nil }
return temp }
}
}
我稍后会用这个得到所有的键。
let componentsArray = dict.allKeys()