Swift: declare an empty dictionary
var emptyDictionary = [String: String]()
var populatedDictionary = ["key1": "value1", "key2": "value2"]
Note: if you're planning to change the contents of the dictionary over time then declare it as a variable (var
). You can declare an empty dictionary as a constant (let
) but it would be pointless if you have the intention of changing it because constant values can't be changed after initialization.
How to create and add values to Dictionary in swift
This is a known issue, apparently not fixed yet (see Is it possible to have a dictionary with a mutable array as the value in Swift)
The workaround would be to create a new variable with your array and then assign it back:
var dict = [String: AnyObject]()
dict["GenInfo"] = ["FirstName":"first","LastName":"last","Phone":"phone"]
dict["Language"] = ["langage1", "langage2"]
if var languages = dict["Language"] as? [String] {
languages.append("langage3")
dict["Language"] = languages
}
Making a Dictionary in Swift
I finally found it out how can i do it.
I use a struct with what I want like this:
var userDictionary = [Int : Event]()
struct Event {
var nameEvent: String
var nameMagazi: String
}
And then i use this:
if let objects = objects {
for object in objects {
let post = object["idEvent"] as? PFObject
let post2 = post!["idMagazi"] as? PFObject
let nameEvent = post!["name"] as! String
let idEvent = post?.objectId
let nameMagazi = post2!["name"] as! String
self.events[self.i] = Event(nameEvent: nameEvent , nameMagazi: nameMagazi)
self.i += 1
}
print(self.events[1]!.nameEvent)
}
Thank you all for your answers!
Dictionary in Swift
In Swift, you can declare and initialize an empty Dictionary with type String
for keys and type Any
for values in 4 different ways:
var myDic1 = [String : Any]()
var myDic2 = Dictionary<String, Any>()
var myDic3: [String : Any] = [:]
var myDic4: Dictionary<String, Any> = [:]
These will all give you the same result which is an empty Dictionary with String
s as the keys and Any
s as the values.
[String : Any]
is just shorthand for Dictionary<String, Any>
. They mean the same thing but the shorthand notation is preferred.
In cases 1 and 2 above, the types of the variables are inferred by Swift from the values being assigned to them. In cases 3 and 4 above, the types are explicitly assigned to the variables, and then they are initialized with an empty dictionary [:]
.
When you create a dictionary like this:
var myDic5 = [:]
Swift has nothing to go on, and it gives the error:
Empty collection literal requires an explicit type
Historical Note: In older versions of Swift, it inferred [:]
to be of type NSDictionary
. The problem was that NSDictionary
is an immutable type (you can't change it). The mutable equivalent is an NSMutableDictionary
, so these would work:
var myDic6: NSMutableDictionary = [:]
or
var myDic7 = NSMutableDictionary()
but you should prefer using cases 1 or 3 above since NSMutableDictionary
isn't a Swift type but instead comes from the Foundation framework. In fact, the only reason you were ever able to do var myDic = [:]
is because you had imported the Foundation framework (with import UIKit
, import Cocoa
, or import Foundation
). Without importing Foundation, this was an error.
Syntax to create Dictionary in Swift
No, both are same.
From Apple's Book on Swift:
The type of a Swift dictionary is written in full as
Dictionary<Key, Value>
You can also write the type of a dictionary in shorthand form as[Key: Value]
. Although the two forms are functionally identical, the shorthand form is preferred.
So
var randomDict = [Int:Int]()
and
var randomDict = Dictionary<Int, Int>()
both calls the initializer which creates an empty dictionary and are basically the same in different form.
Create Dictionary from Array in Swift 5
You can do a map
, and then individually change the type of the first dictionary:
var dicts = urlArray.map { ["name": $0, "type": "B"] }
dicts[0]["type"] = "A"
Seeing how all your dictionary keys are all the same, and that you are sending this to a server, a Codable
struct might be a better choice.
struct NameThisProperly : Codable {
var name: String
var type: String
}
var result = urlArray.map { NameThisProperly(name: $0, type: "B") }
result[0].type = "A"
do {
let data = try JSONDecoder().encode(result)
// you can now send this data to server
} catch let error {
...
}
Different ways to declare a dictionary in Swift?
They both do the same thing to declare and initialize an empty dictionary of that key and value type.
Apple documents the first way in their Swift Guide. (Scroll down to Dictionaries section).
The second way you show is simply more formal, which may help those new to Swift who don’t know the dictionary shorthand/literal syntax.
The
Different ways to initialize a dictionary in Swift?
All you're doing is noticing that you can:
Use explicit variable typing, or let Swift infer the type of the variable based on the value assigned to it.
Use the formal specified generic struct notation
Dictionary<String,Double>
, or use the built-in "syntactic sugar" for describing a dictionary type[String:Double]
.
Two times two is four.
And then there are in fact some possibilities you've omitted; for example, you could say
var dict5 : [String:Double] = [String:Double]()
And of course in real life you are liable to do none of these things, but just assign an actual dictionary to your variable:
var dict6 = ["howdy":1.0]
How to make a dictionary containing dictionaries in swift
Creating a nested dictionary in Swift is easy. In its simplest form, the most intuitive way is:
let dict = ["key": ["nestedKey": ":)"]]
In your case, for starters, your quotations are mismatched.
Next, you're overthinking what a dictionary is and how you instantiate it. You're trying to build a predefined dictionary with nested keys (which are actually immutable). If you want to do it your way, don't worry about pre-defining keys. When you're ready to assign, do:
var days: [String: Dictionary] = []
days["ADay"] = [1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7]
If you need something more complex, or something more structured than that, try using a Struct instead. This is the "Swift" way of doing things, allowing you to structure a complex set of conforming (statically typed!) data. Example:
struct Days {
var ADay = [Int: Int]()
var BDay = [Int: Int]()
var CDay = [Int: Int]()
var DDay = [Int: Int]()
}
var days = Days()
days.ADay = [1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7]
Related Topics
Is There an Object Class in Swift
Add Custom .Colornames to UIcolor Somehow
Nsdocumentcontroller.Opendocument Not Allowing Selection of Custom File Type
Query Value Between Two Other Values in Firebase
How to Get Parallax Effect on UIbutton in Tvos
Convert Data to Dispatchdata in Swift 4
Understanding UIviewrepresentable
Possible Bug? I Can Create Generic Instance Ignoring Constraint
Didupdateheading Not Called in Swift
Same Object Different Address. Why
Difference Between Timestamp Stored and Current Date
Sprite Kit Game Crashes on Game Over on Tvos 9.1 and iOS 9.2
Passing Core Data Objects from UItableviewcell to Another View Controller