2016-09-21 57 views
0

要存儲數據到我的火力點,我用下面的代碼:斯威夫特/ NSMutableDisctionary的init /如何使價值可選

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

我想freeclub到:

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

通過調用是可選的,這樣我就可以將它們設置nil這樣的: saveDateToFirebase(formatter.stringFromDate(date), free: nil, club: nil)

什麼是重的最佳實踐改變?非常感謝幫助。

PS:free: "true", club: "11er"已經過硬編碼測試。

PPS:我試過設置init (date: String, free: String?, club: String?),但Xcode中迫使我解開他們以後...

回答

0

我是能夠使他們可選的(能夠把他們無)一點點的解決方法:

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

} 

現在,我可以這樣調用:

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

,最終使他們nil,如果我想太多:

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