In Stanford's class(see the picture 1), the professor initialized a Dictionary like this:
var a = Dictionary<String: Int>()
But it cannot work in my computer(see the picture 2), is there something wrong?
Dictionary is a generic struct, whose generic type parameters can be defined in the same way as any other generic struct, using a comma separated list in angle brackets:
let a = Dictionary<String, Int>()
There's also a special syntactic sugar that's specific to dictionaries, that let you express the same as above as:
let a = [String: Int]()
Mixing the two together as in Dictionary<String: Int> is invalid.
Related
I am trying to create a particular data structure as specified below in Swift.
[{"productId":1,"qty":3},{"productId":2,"qty":1},{"productId":3,"qty":5},{"productId":4,"qty":30},{"productId":5,"qty":13}]
Can some one guide me how to achive it..... I need to add and remove the data structure.
Thanks in advance.....
It is an Array of Dictionaries.
Define it like this :
var dataStructure = [[String: Any]]()
To add something :
var newData = [String: Any]()
newData["productId"] = 1
newData["qty"] = 1
dataStructure.append(newData)
To delete :
dataStructure.remove(at: indexYouWantTodeleteInInt)
It is called as dictionary in swift.
The declaration part can be as follows:
var params: [String:Any]
We can also use like:
var params: [String:Any] = ["user_id" : AppConfiguration.current.user_id]
Now to add key-value pair in it you can do as follows:
params["form_id"] = form_id!
params["parent_category_id"] = id
params["device_token"] = getDeviceToken()
params["app_version"] = APP_VERSION
params["app_device_type"] = originalDeviceType
to remove a key-value pair:
params.removeValue(forKey: "parent_category_id")
to update any value of particular key:
params.updateValue("10", forKey: "form_id")
if the above key is already present it updates the value and if not then it adds a new key to the dictionary
The Above explained part is dictionary. Now you need the data-structure as array of dictionary so you need to declare as
var params: [[String:Any]]
you can perform all the operations you can perform on an array but the value you will get at a particular index will be of type dictionary which I explained above.
Hope this helps you understand what is dictionary and what is array of dictionaries.
In your case you can also write [String: Int] instead of `[String:Any]' but it will restrict you to only have integer values with respect to the keys.
Swift developers usually use Structs in order to create a data structure from a JSON reponse. From Swift 4, JSON parsing has become very easy. Thanks to Codable protocols.
From the above given answer, you can create something like this.
MyStruct.Swift
import Foundation
typealias MyStruct = [[String: Int]]
You can then parse by calling the following method.
let myStruct = try? JSONDecoder().decode(MyStruct.self, from: jsonData)
You can add value by using this.
var newProduct = [String: Any]()
newProduct["productId"] = 941
newProduct["qty"] = 2
myStruct.append(newProduct)
To remove the data
myStruct.remove(at:"Some index")
Is there a way to have named key/value pairs in a Swift dictionaries? I'd rather use a name instead of an index number to refer to either the key or the value.
Unfortunately, key/value pairs by name in Dictionary in Swift only discusses referring to the keys and values in a for-loop. I'd like to give the keys and values a name when I declare them in the typealias so they can always be referred to by their names.
Please see the comment in the below code snippet to show what I mean:
typealias CalendarRules = [EKCalendar : [String]]
let calendarRules = buildCalendarRules() // builds the array.
let firstCalendarRule = calendarRules.first
print(firstCalendarRule.0) // I'd like to write: print(firstCalendarRule.cal)
print(firstCalendarRule.1) // I'd like to write: print(firstCalendarRule.theString)
This has nothing to do with dictionaries, except very indirectly; and your CalendarRules type alias is irrelevant. Your firstCalendarRule is not a dictionary; it is a tuple. You are free to name the members of a tuple:
typealias Rule = (cal:String, string:String)
let d = ["I am a calendar":"I am a string"]
let firstRule : Rule = d.first!
print(firstRule.cal) // I am a calendar
I want to create a NSDictionary with multiple key-value pairs and different value-types. My main question is how can i add a simple (2 item)-Tuple and a NSString to a NSDictionary?
Just adding a String or even a Tuple to a NSDictionary is simple.
But to add both is complicated.
I tried this:
var myTuple = (longitude: -122.1234, latitude: 55.1234)
var aPersonDictionary: [String:AnyObject] = ["firstname":"Sally", "age":45, "location":myTuple]
But this does not work. It gives me the error: Value of type '(longitude: Double, latitude: Double') does not conform to expected dictionary value type 'AnyObject'.
I don't understand that because AnyObject is everything
Any help is highly appreciated
Actually AnyObject is not everything. It's representing an instance of any class type. Therefore, the thing you would like to have could be Any which can represent an instance of any type at all, including function types.
var myTuple = (longitude: -122.1234, latitude: 55.1234)
var aPersonDictionary: [String : Any] = ["firstname":"Sally", "age":45, "location":myTuple]
You should use Any instead of AnyObject because AnyObject is used for instances of a class type (which a tuple is not), it should be:
myTuple = (longitude: -122.1234, latitude: 55.1234)
var aPersonDictionary: [String:Any] = ["firstname":"Sally", "age":45, "location":myTuple]
Further explanation:
AnyObject can represent an instance of any class type.
Any can represent an instance of any type at all, apart from function types.
I'm pretty new to Swift and need your help on a (probably) pretty basic problem.
I have a dictionairy:
var dict = ["title" : "Title", "Features" : ["feat1", "feat2", "feat3"], ...]
I can create a string from it like so:
var headline = dict["title"]! as string
but I couldn't manage to create an array. I tried in various combinations:
var features = dict["Features"]
var features = dict["Features"]! as Array
var features: Array = dict["Features"]
So please enlighten me! How do create an array? Is it possible at all?
You should specify the type for the array. Either
let features = dict["Features"] as [String]
or
let features = dict["Features"] as Array<String>
See the discussion of collection types in The Swift Language.
Your problem is that you don't have a type for the array. You describe the type of an array in swift by putting the type name in brackets. In your case, this will be [String]. Thus, your code should be var features = dict["Features"] as [String] for a mutable array, or use let for an immutable array. Hope this helps.
I'm getting this error in XCode beta 3. Don't know whether this is a bug or if I'm doing something I shouldn't. Anyway, this is an example that I read on Apple's official documentation.
Here's the code:
var names = ["Mark" , "Bob" , "Tracy" , "John"]
var reversed = sort(names , { (s1: String , s2: String) -> Bool in return s1 > s2
})
It is a simple sort using a closure.
There are several problems here:
Never declare a generic without specifying its type. Don't use Array, use Array<String>. However, in this case, you don't need the : Array<String part, you don't need the typing as Array<String>. Just let the type be inferred.
let names = ["Mark", "Bob", "Tracy", "John"]
Now, this is a constant array. Array is a value type. Constant value types cannot be modified.
The sort function is trying to sort the array. It doesn't create a new array, it sorts the one you pass as a parameter. However, since it is a value type, it cannot be a constant and you have to pass it by reference:
var names = ["Mark", "Bob", "Tracy", "John"]
sort(&names, >)
If you don't want to sort the original array and you want to create a new array instead, use sorted function.
let names = ["Mark", "Bob", "Tracy", "John"]
let sortedNames = sorted(names, >)
Note this has changed substantially between Beta 2 and Beta 3.