How to create NSMutableDictionary in swift 2.0
Simply by opening NSMutableDictionary
or NSDictionary
class interfaces from Xcode 7, you could easily see that the underlying type is actually [NSObject: AnyObject]
. It means that the value can't be nil
.
Unwrapping text values like txtEmail.text!
or txtPassword.text!
might look ok and help you to get rid of the compiling error, but it's a bad choice because technically text
property of UITextField
is optional and your app can crash in that case!
Do this for your safety:
let dictParams: NSMutableDictionary? = ["test" : "test",
"username" : txtEmail.text ?? "", // Always use optional values carefully!
"password" : txtPassword.text ?? "",
"version" : "1.0",
"appId" : "1",
"deviceId" : "fasdfasdfrqwe2345sdgdfe56gsdfgsdfg"
]
By the way, in case it's not critical to use NSMutableDictionary
, please consider using Swift dictionary like this:
var mutableDictionary = [String: AnyObject]
// OR this if the value can be nil
var mutableDictionary = [String: AnyObject?]
How to add field to NSMutableDictionary Swift
Use Dictionary
in swift instead of NSDictionary
. Also, you need to give the type
while declaring the Dictionary
variable.
Try this:
var villages = [[String : Any]]()
var bars = [[String : Any]]()
var allBars = [[String : Any]]()
//And this
bars[2]["Distance"] = distanceInMiles
bars[2]
in the above code will only work if the array bars
has atleast 3 elements in it. Otherwise it will give "Array index out of bounds"
exception.
Swift Dictionary [String:String] to NSMutableDictionary?
There’s no built-in cast for this. But instead you can use NSMutableDictionary
’s initializer that takes a dictionary:
var foundationDictionary = NSMutableDictionary(dictionary: dictionary)
How to add NSMutableDictionary values in NSMutableArray
If your arrVideoRange
is NSMutableArray
like this
var arrVideoRange : NSMutableArray = []
then try this
for value in videoRangeDic.allValues{
arrVideoRange.addObjects(from: value as [Any])
}
Swift equivalent to `[NSDictionary initWithObjects: forKeys:]`
As of Swift 4 you can create a dictionary directly from a
sequence of key/value pairs:
let keys = ["one", "two", "three"]
let values = [1, 2, 3]
let dict = Dictionary(uniqueKeysWithValues: zip(keys, values))
print(dict) // ["one": 1, "three": 3, "two": 2]
This assumes that all keys are different, otherwise it will abort
with a runtime exception.
If the keys are not guaranteed to be distinct then you can do
let keys = ["one", "two", "one"]
let values = [1, 2, 3]
let dict = Dictionary(zip(keys, values), uniquingKeysWith: { $1 })
print(dict) // ["one": 3, "two": 2]
The second argument is a closure which determines which value "wins"
in the case of duplicate keys.
Swift - Append to NSMutableDictionary
Yes you are actually replacing the RSVPDirectory[firstLetter]
, overriding it every time with new tmp
.
What you are looking for is this:
//RSVPDirectory[firstLetter] = tmp //Replace this line with below code
let tempArray = RSVPDirectory[firstLetter] as? [AnyHashable]
tempArray?.append(tmp)
RSVPDirectory[firstLetter] = tmpArray
Here I have used a tempArray
because we want to mutate the array. Accessing it directly and trying to append new value will in-turn try to mutate an immutable value. So first I have got the array in the tempArray
and then after mutating the array I swapped it back in the dictionary with updated values.
How to create and access a NSDictionary in Swift
The issue is actually that a subscript lookup for a Dictionary
in Swift returns an optional value:
This is a pretty great feature - you can't be guaranteed that the key you're looking for necessarily corresponds to a value. So Swift makes sure you know that you might not get a value from your lookup.
This differs a little bit from subscript behavior for an Array
, which will always return a value. This is a semantically-driven decision - it's common in languages for dictionary lookups to return null
if there is no key - but if you try to access an array index that does not exist (because it's out of bounds), an exception will be thrown. This is how Swift guarantees you'll get a value back from an array subscript: Either you'll get one, or you'll have to catch an exception. Dictionaries are a little more lenient - they're "used to" not having the value you're asking for.
As a result, you can use optional binding to only use the item if it actually has a value, like so:
if let theArray = dictionary["MainString1"] {
let item0 = theArray[0]
} else {
NSLog("There was no value for key 'MainString1'")
}
swift: Add multiple key, value objects to NSDictionary
You can definitely make a dictionary of dictionaries. However, you need a different syntax for that:
var myDictOfDict:NSDictionary = [
"a" : ["fname": "abc", "lname": "def"]
, "b" : ["fname": "ghi", "lname": "jkl"]
, ... : ...
]
What you have looks like an array of dictionaries, though:
var myArrayOfDict: NSArray = [
["fname": "abc", "lname": "def"]
, ["fname": "ghi", "lname": "jkl"]
, ...
]
To get JSON that looks like this
{"Data": [{"User": myDict1}, {"User": myDict1},...]}
you need to add the above array to a dictionary, like this:
var myDict:NSDictionary = ["Data" : myArrayOfDict]
Related Topics
How to Hash a String to Sha512 in Swift
Swift Firebase Custom Object with Document Id
From the Swift Repl, How to Get a List of Available Modules
How to Do a Long Press in Swift
How to Draw Two Polylines in Different Colors in Mapkit
Implicitlyunwrappedoptional in Init VS Later
Using Vapor-Fluent to Upsert Models
Scenekit Physics Add Velocity in Local Space
Nspopover to Start in a Detached State
Add Datepicker in Uiactionsheet Using Swift
How to Star a Repo with Github API
How to Access Cfdictionary in Swift 3
Building for Arm64E on Apple Silicon
Realmswift + Multiple Predicate
A Swiftier Way to Convert String to Unsafepointer<Xmlchar> in Swift 3 (Libxml2)
How to Prevent a Spacer to Make a VStack Greedly Grow Beyond Necessary