iOS Swift - Declare external function inside @IBAction func

761 Views Asked by At

I need to call some other function when UIButton is pressed (in my case pass data from UIDatePicker and UITextField to EKCalendar to create an event, so I can not just write it inside IBAction func {}) Here is my function:

func insertEvent(store: EKEventStore) {

        let calendars = store.calendarsForEntityType(EKEntityTypeEvent)
            as! [EKCalendar]

        for calendar in calendars {

            if calendar.title == "todo" {

                let startDate = myDatePicker.date

                let endDate = startDate.dateByAddingTimeInterval(2 * 60 * 60)

                // Create Event
                var event = EKEvent(eventStore: store)
                event.calendar = calendar

                event.title = nameTextField.text
                event.startDate = startDate
                event.endDate = endDate

                // Save Event in Calendar
                var error: NSError?
                let result = store.saveEvent(event, span: EKSpanThisEvent, error: &error)

                if result == false {
                    if let theError = error {
                        println("An error occured \(theError)")
                    }
                }
            }
        }
    }

What should I write in :

@IBAction func addReminder(sender: UIButton) {

}

to call my function I wrote above.

I've tried just call it by typing insertEvent() inside IBAction func {}, but in gives me warning "missing argument for parameter #1 in call..." also tried to call in with parameter and it also gives me warning... I also tried to create an outlet for button (not action) type of segue and then access in with

func addReminder(sender: UIButton) { 
    if sender === addReminder {}
} 

but it gives me the same errors... what a curse!

How could I assign this function to a button, maybe there is another way?

P.S.: I am Xcode 6.3

1

There are 1 best solutions below

2
AudioBubble On

The issue you are facing is in how you declared insertEvent. You have two options.

Declare it like you have - but understand you need to declare the parameter in your call:

func insertEvent(store: EKEventStore) {
    // do something here
}

And to call it:

@IBAction func addReminder(sender: UIButton) {
    insertEvent(store: myEKEventStoreVariable)
}

The more "Swiftier" way is to put an underscore in your function declaration, which makes the function call no need the parameter:

func insertEvent(_ store: EKEventStore) {
    // do something here, again, note the underscore
}

And the call is:

@IBAction func addReminder(sender: UIButton) {
    insertEvent(myEKEventStoreVariable)
}

Essentially you were correct - you cannot "embed" the function declaration inside your IBAction, so you needed to move that logic into an "outside" function. But you declared the function in a way to require the parameter name.