Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift iOS 8, first value of NSDictionary

Tags:

swift

iphone

ios8

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

thanks,

like image 625
PatrickFeng Avatar asked Dec 16 '14 03:12

PatrickFeng


People also ask

What is NSDictionary in Swift?

In Swift, the NSDictionary class conforms to the DictionaryLiteralConvertible protocol, which allows it to be initialized with dictionary literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).

How do you add value in NSMutableDictionary?

You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil). The simplified form mentioned above, usually solves problems OCLint (metric static code analysis).

What is NSMutableDictionary in Swift?

The NSMutableDictionary class declares the programmatic interface to objects that manage mutable associations of keys and values. It adds modification operations to the basic operations it inherits from NSDictionary . NSMutableDictionary is “toll-free bridged” with its Core Foundation counterpart, CFMutableDictionary .

Why is dictionary unordered in Swift?

Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations. Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store. This means that you can't insert a value of the wrong type into a collection by mistake.


2 Answers

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

or:

let v = dict.allValues[0] as! String
like image 95
vacawama Avatar answered Oct 27 '22 03:10

vacawama


Cast to a Swift Dictionary if it isn't one already. Then use the values property, cast to an Array, and get index 0.

let v = Array(myDictionary.values)[0]
like image 7
matt Avatar answered Oct 27 '22 05:10

matt