I have NSDictionary, I know it only has one key and one value, how can I directly get the first value from it?
thanks,
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).
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).
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 .
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.
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With