简体   繁体   中英

How to map array to a key in dictionary in swift?

I want to create a dictionary with key as date & array of events.A date can have multiple events so i want to map one date as key of dictionary to the array of string.I will be dynamic a date can have no events or a date can have multiple events.I am getting data from array of dates i need to map it with events.

I have tried below code:

func addEventToDictionary(eventModal:CalenderEventModal,date:Date) {
    var key:String = self.dateFormatter().string(from: date)

    if let val = dict_events[key] {

    } else {
        dict_events[key]  = [Any]()
    }

    dict_events[key] = eventModal
}

Here Event modal is an Object of Event.

Assuming dict_events is a dictionary with a declared type of [String: [Any]] , then I believe all you're missing is appending to this array instead of assigning it. The value portion of the dictionary is Optional, so you need to append the value to a non-Optional array, then assign this back into your dictionary's key . Also, if you know you're only going to be storing CalenderEventModal objects, you could change the type of dict_events to [String: [CalenderEventModal]] . The fix for your code would look like this:

var dict_events: [String: [CalenderEventModal]] = [:]

func addEventToDictionary(eventModal: CalenderEventModal, date: Date) {
    var key: String = self.dateFormatter().string(from: date)

    if var val = dict_events[key] {
        val.append(eventModal)
        dict_events[key] = val
    } else {
        let events = [CalenderEventModal]()
        events.append(eventModal)
        dict_events[key] = events
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM