I built a @FunctionalProtocol macro that generates zero-cost wrapper structures for Single Abstract Method (SAM) protocols.
Currently, this is a proof of concept, so please let me know if you feel like you are missing something, or if you think this specific use case is too much of an edge case to warrant its own macro.
How it can look like:
@FunctionalProtocol
public protocol Transformer {
associatedtype Input
associatedtype Output
func transform(_ input: Input) -> Output
}
// That's all. Now use it:
processData(use: .transform { $0.uppercased() })
I hope this can close a syntax gab and avoid the keyword hell in Parameter lists of some functions.
This is a convenient syntax but note that It’s not zero cost at all if the closure captures anything other than a swift object as closures heap allocate their storage.
A struct can store its “context” in stored properties which are all stored inline which can make a huge difference.
You're right, but compared to a closure in the parameter list, the wrapper struct can be completely optimized away. This gives you the conformance of a protocol with a closure without the additional overhead.
I had considered using structs as closures, but currently we need the flexibility of the closure. Perhaps someday, after the new lifetimes and zero-cost abstractions, we'll get stack closures like in Rust.