qwerty_so
qwerty_so

Reputation: 36305

Get [String] from NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys

NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys returns [NSObject] but I need (and would expect) [String]. Is it just some coffee I'm missing?

Upvotes: 2

Views: 801

Answers (2)

Nate Cook
Nate Cook

Reputation: 93276

That actually returns a LazyBidirectionalCollection<MapCollectionView<Dictionary<Key, Value>, Key>>. You can add .array to get an array instance back, then use map to cast the values to String:

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

Upvotes: 1

Kirsteins
Kirsteins

Reputation: 27335

dictionaryRepresentation() returns NSDictionary that does not support generic types. You can convert to Swift dictionary:

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

Upvotes: 3

Related Questions