David Seek David Seek - 2 months ago 9
Swift Question

Swift / NSMutableDisctionary init / How to make value optional

To store data into my firebase I'm using the following Code:

class NewEventDate {

private let firebase = FIRDatabase.database().reference().child("eventDates")
let eventDictionary: NSMutableDictionary

init (date: String, free: String, club: String) {

eventDictionary = NSMutableDictionary(objects: [date, free, club], forKeys: ["date", "free", "club"])
}

func saveEventDate(backendlessUserObjectID: String, item: NSMutableDictionary) {

let reference = firebase.child(backendlessUserObjectID)
reference.setValue(item) { (error, ref) -> Void in
if error != nil {
SpeedLog.print("\(error)")
}
}
}
}


Called by:

func saveDatesLoop() {

for date in calendarView.selectedDates {
saveDateToFirebase(formatter.stringFromDate(date), free: "true", club: "11er")
}
}

func saveDateToFirebase(date: String, free: String, club: String) {

var newEvent = NewEventDate?()
newEvent = NewEventDate(date: date, free: free, club: club)
newEvent?.saveEventDate(backendless.userService.currentUser.objectId, item: newEvent!.eventDictionary)
}


I want
free
and
club
to be optional, so I can set them
nil
like that:
saveDateToFirebase(formatter.stringFromDate(date), free: nil, club: nil)


What's the best practice to realize that? Help is very appreciated.

PS:
free: "true", club: "11er"
is hard coded to test.

PPS: I've tried to set
init (date: String, free: String?, club: String?)
, but Xcode forces me to unwrap them later on...

Answer

I was able to make them optional (to be able to put them nil) with a little workaround:

init (date: String, free: String?, club: String?, eventText: String?) {
    var localFree = ""
    var localClub = ""
    var localEventText = ""

    if let tempFree = free {
        localFree = tempFree
    }
    if let tempClub = club {
        localClub = tempClub
    }
    if let tempEventText = eventText {
        localEventText = tempEventText
    }

    eventDictionary = NSMutableDictionary(objects: [date, localFree, localClub, localEventText], forKeys: ["date", "free", "club", "eventText"])

}

Now I can call it like this:

func saveDateToFirebase(date: String, free: String?, club: String?, eventText: String?) {

    var newEvent = NewEventDate?()
    newEvent = NewEventDate(date: date, free: free, club: club, eventText: eventText)
    newEvent?.saveEventDate(backendless.userService.currentUser.objectId, date: date, item: newEvent!.eventDictionary)
}

And finally make them nil if I want too:

saveDateToFirebase(NSDate(), free: nil, club: nil, eventText: nil)