从NSUserDefaults.standardUserDefaults()。dictionaryRepresentation()。获取[String]。

时间:2014-12-16 15:29:29

标签: string swift dictionary nsobject

NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys返回[NSObject],但我需要(并期望)[String]。我只是喝了一些咖啡吗?

2 个答案:

答案 0 :(得分:3)

dictionaryRepresentation()返回不支持泛型类型的NSDictionary。您可以转换为Swift词典:

let dictionary = NSUserDefaults.standardUserDefaults().dictionaryRepresentation() as [String : AnyObject]
let keys = dictionary.keys

答案 1 :(得分:1)

实际上返回LazyBidirectionalCollection<MapCollectionView<Dictionary<Key, Value>, Key>>。您可以添加.array以获取数组实例,然后使用map将值转换为String

let keys = NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array.map { $0 as String }
println(keys)
// [NSLanguages, NSInterfaceStyle, AppleLanguages]