0

In Objective-C, you could specify the event handler for a dispatch source as either a block or a function. From Apple's Concurrency Programming Guide:

Function-based event handlers take a single context pointer, containing the dispatch source object, and return no value. Block-based event handlers take no parameters and have no return value.

In Swift 3, is it still possible to use a function as an event handler? I only see how to use a block. I need access to the source in my handler and I need to define my handler separately from where the source is defined.

1 Answer 1

1

How about this?

class Foo {
    var eventHandler: (DispatchSourceRead) -> Void
    init(handler: @escaping (DispatchSourceRead) -> Void) {
        eventHandler = handler
    }
}

let foo = Foo() { source in
    print("got event from source")
}

let source = DispatchSource.makeReadSource(fileDescriptor: 0)
source.setEventHandler {
    foo.eventHandler(source)
}
Sign up to request clarification or add additional context in comments.

2 Comments

You are using the block event handler, but you've written it so as to capture the source? Is that right? Could you have also done something like: let foo: (DispatchSourceRead) -> Void = { source in print("hi \(source)") } and then source.setEventHandler { foo(source) }? In other words, why do you need class Foo?
You don't need the class. That was my first thought as to why you needed it defined away from the source. To prevent the capture, you can add a capture list to the event handler that uses a weak reference to source.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.