Wednesday, 25 October 2017

Deep: Dictionary code


1. Declaring Empty Dictionary
------------------------------------------------------------------------------------------

var emptyDict = [String: String]()
var emptyDict = Dictionary<String, String>()
var emptyDict: [String: String] = [:]
var emptyDict: [String: String] = [String: String]()
var emptyDict: [String: String] = Dictionary<String, String>()
var emptyDict: Dictionary = [String: String]()
var emptyDict: Dictionary = Dictionary<String, String>()
var emptyDict: Dictionary<String, String> = [:]
var emptyDict: Dictionary<String, String> = [String: String]()
var emptyDict: Dictionary<String, String> = Dictionary<String, String>()
NOTE :-

After you have an empty Dictionary you can add a key-value pair like this:
emptyDict["some key"] = "some value"
If you want to empty your dictionary again, you can do the following:
emptyDict = [:]
The types are still <String, String> because that is how it was initialized.
If you wanted to initialize an array of an empty dictionary, you'd do it as such: var emptyDictArray = [[String: String]()] var emptyDictArray = [Dictionary<String, String>()]
Declare AnyObject
var myDictionary = Dictionary<String, AnyObject>()
But you can create a Dictionary that accepts different value types by using the "Any" type like so :
var emptyDictionary = Dictionary<String, Any>()
 
------------------------------------------------------------------------------------------

2.

------------------------------------------------------------------------------------------
3. Sort Dictionary on single key basis

I think you're looking for sortdescriptor in objective C, it's much more easier in swift since the Array type has a method sorted try this code it worked for me:
var myArray = Array<Dictionary<String, String>>()
var dict = Dictionary<String, String>()

dict["a"] = "hickory"
dict["b"] = "dickory"
dict["c"] = "dock"

myArray.append(dict)

dict["a"] = "three"
dict["b"] = "blind"
dict["c"] = "mice"

myArray.append(dict)

dict["a"] = "larry"
dict["b"] = "moe"
dict["c"] = "curly"

myArray.append(dict)

println(myArray[0])
println(myArray[1])
println(myArray[2])

var sortedResults = myArray.sorted {
  (dictOne, dictTwo) -> Bool in 
  return dictOne["c"]! < dictTwo["c"]!
};
println(sortedResults);
EDIT
I changed the dictionary type because I saw that you were only using Strings. In a general case with AnyObject all you need is to cast before making the comparison:
var sortedResults = myArray.sorted {
  (dictOne, dictTwo) -> Bool in 
  let d1 = dictOne["d"]! as Int;
  let d2 = dictTwo["d"]! as Int;

  return d1 < d2

};
println(sortedResults);
Best of luck.

No comments:

Post a Comment