Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Dictionary in Swift

I have an object taken from Parse and I want to save its columns into a Dictionary or something else (if it's better).

I want to have a Dictionary like this: ["name" : "Mike", "lastname" : "vorisis", "id" : "advsas"]

Below is the code I use to take my results:

func queryEvents() {
    let query = PFQuery(className: "eventController")
    query.limit = 1000
    query.includeKey("idEvent")
    query.includeKey("eventType")
    query.includeKey("idEvent.idMagazi")
    query.findObjectsInBackgroundWithBlock { (objects, error)-> Void in
        if let objects = objects  {
            for object in objects {
                var post = object["idEvent"] as? PFObject
                var post2 = post!["idMagazi"]
                print("retrieved related post: \(post2["name"]!)")
            }
        }
    }
}
like image 766
mike vorisis Avatar asked Jul 06 '16 08:07

mike vorisis


People also ask

What is dictionary in Swift?

Swift dictionary is an unordered collection of items. It stores elements in key/value pairs. Here, keys are unique identifiers that are associated with each value.

How do I print a dictionary in Swift?

To print all the keys of a dictionary, we can iterate over the keys returned by Dictionary. keys or iterate through each (key, value) pair of the dictionary and then access the key alone.

How do I read a dictionary in Swift?

Example 1 – Get Value in Dictionary using Key In this example, we shall create a dictionary with initial values, and access the values from this dictionary using keys. var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79] var mohanScore = myDictionary["Mohan"] print("value is: \(mohanScore!)")

How to create an empty dictionary in Swift?

To create an empty dictionary in Swift, use the following syntax, ValueType is the datatype of the value in (key, value) In the following example, we create a dictionary that has a key of Int type and value of Int type. In the following example, we create a dictionary that has a key of Int type and value of String type.

What is swift Dictionary?

Swift dictionary is an unordered collection of items. It stores elements in key/value pairs. Here, keys are unique identifiers that are associated with each value.

How to iterate over the elements of a dictionary in Swift?

We use the for loop to iterate over the elements of a dictionary. For example, We can use the count property to find the number of elements present in a dictionary. For example, In Swift, we can also create an empty dictionary. For example, In the above example, we have created an empty dictionary. Notice the expression

Can you change the size of a dictionary Swift?

Swift - Dictionaries. If you assign a created dictionary to a variable, then it is always mutable which means you can change it by adding, removing, or changing its items. But if you assign a dictionary to a constant, then that dictionary is immutable, and its size and contents cannot be changed.


3 Answers

Something else (if it's better) is a custom class. Change the type of idMagazi to the real type.

class Event {

  let post : PFObject
  let name : String
  let idMagazi : String

  init(object : PFObject) {
    self.post = object
    self.name = object["name"] as! String
    self.idMagazi = object["idMagazi"] as! String

  }
}

And use it

 ...
 if let objects = objects as? [PFObject]  {
    var events = [Event]()
    for object in objects {

      let post = Event(object: object)
      events.append(post)
      print("retrieved related post: \(post.name)")
    }
 }
 ...
like image 65
vadian Avatar answered Oct 17 '22 10:10

vadian


In Swift Dictionary<T,V> is equivalent to [T: V]. Type is inferred if not explicitly declared.

Empty dictionary creation (all equivalent):

var dict1: Dictionary<String, String> = [:]
var dict2: [String: String] = [:]
var dict3 = Dictionary<String, String>()
var dict4 = [String: String]()

Dictionary with values (all equivalent):

var dict5 = ["Foo": "Bar", "Foo1": "Bar1", "Foo2": "Bar2"]
var dict6: Dictionary<String, String> = ["Foo": "Bar", "Foo1": "Bar1", "Foo2": "Bar2"]
var dict7: [String: String] = ["Foo": "Bar", "Foo1": "Bar1", "Foo2": "Bar2"]

Add values to an existing dictionary:

dict["Foo"] = "Bar"

In your specific scenario, you could use this:

let dict = ["name" : name, "lastname" : lastname , "id" : id]

where name, lastname and id are String variables.


Update based on your own answer:

Having this struct:

struct Event {
    var nameEvent: String
    var nameMagazi: String
}

You can use this approach, that avoid having an external index and uses an array instead of a dictionary for storing the results.

var events: [Event]?

guard let objects = objects else { return }
events = objects.map { object in
    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

    return Event(nameEvent: nameEvent , nameMagazi: nameMagazi)
}
like image 25
redent84 Avatar answered Oct 17 '22 09:10

redent84


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!

like image 5
mike vorisis Avatar answered Oct 17 '22 11:10

mike vorisis