在 Swift 3 中,Dictionary 有一个 keys 属性。 keys 有以下声明:
var keys: LazyMapCollection<Dictionary<Key, Value>, Key> { get }
仅包含字典键的集合。
请注意,LazyMapCollection 可以通过 Array 的 init(_:) 初始化程序轻松映射到 Array。
从NSDictionary 到[String]
以下 iOS AppDelegate class sn-p 展示了如何使用 keys 属性从 NSDictionary 获取字符串数组 ([String]):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let string = Bundle.main.path(forResource: "Components", ofType: "plist")!
if let dict = NSDictionary(contentsOfFile: string) as? [String : Int] {
let lazyMapCollection = dict.keys
let componentArray = Array(lazyMapCollection)
print(componentArray)
// prints: ["Car", "Boat"]
}
return true
}
从[String: Int] 到[String]
以更一般的方式,以下 Playground 代码显示了如何使用带有字符串键和整数值 ([String: Int]) 的字典中的 keys 属性获取字符串数组 ([String]):
let dictionary = ["Gabrielle": 49, "Bree": 32, "Susan": 12, "Lynette": 7]
let lazyMapCollection = dictionary.keys
let stringArray = Array(lazyMapCollection)
print(stringArray)
// prints: ["Bree", "Susan", "Lynette", "Gabrielle"]
从[Int: String] 到[String]
以下 Playground 代码显示了如何使用 keys 属性从具有整数键和字符串值 ([Int: String]) 的字典中获取字符串数组 ([String]):
let dictionary = [49: "Gabrielle", 32: "Bree", 12: "Susan", 7: "Lynette"]
let lazyMapCollection = dictionary.keys
let stringArray = Array(lazyMapCollection.map { String($0) })
// let stringArray = Array(lazyMapCollection).map { String($0) } // also works
print(stringArray)
// prints: ["32", "12", "7", "49"]