Making a Dictionary in Swift

2020-08-13 03:47发布

问题:

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"]!)")
            }
        }
    }
}

回答1:

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)")
    }
 }
 ...


回答2:

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)
}


回答3:

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!



回答4:

Create dictionary like this:

var dict = ["name" : "Mike", "lastname" : "vorisis" , "id" : "advsas"]

OR

var dict = Dictionary<String,String>
dict.setValue("Mike", forKey: "name")


回答5:

A dictionary can be made using this line:

var dictionaryArray: [Dictionary<String,String,Int>] = []

Then values can be added by appending them to the dictionary.

dictionaryArray.append(["name" : "Mike", "lastname" : "vorisis" , "id" : "advsas"])

Hope this helps.