PatrickFeng PatrickFeng - 1 year ago 38
Swift Question

Swift iOS 8, first value of NSDictionary

I have NSDictionary, I know it only has one key and one value, how can I directly get the first value from it?



If you have a Swift Dictionary and you know you have exactly 1 key/value pair you can do this:

var dict = ["aaa":"bbb"]
let v = dict.values.first!

If you have more than 1 key/value pair then there is no "first" value since dictionaries are unordered. If you have no key/value pairs this will crash.

If you have an NSDictionary, you can use allValues.first!, but you'll have to cast the result because the value will be an AnyObject:

var dict:NSDictionary = ["aaa":"bbb"]
let v = dict.allValues.first! as! String


let v = dict.allValues[0] as! String