Reputation: 29316
In Objective-C it's a pretty common paradigm to use conforming to a protocol and setting a delegate to allow two objects to communicate with one another. Part of this is optional protocols that they don't have to implement.
It seems Swift doesn't really consider this a part of its language. It has protocols but in order to mark a method in a protocol as optional the protocol needs an objc
prefix, telling me that it's also an Objective-C relic?
Is there something we should be doing instead that is more Swift-esque? Passing fancy closures or something?
Upvotes: 4
Views: 509
Reputation: 51911
In this Developer Forums topic:
Optional methods in protocols are limited to @objc protocols only because we haven't implemented them in native protocols yet. This is something we plan to support.
Although you can implement delegate pattern with optional methods in pure Swift, but it's very ugly ...
protocol MyOperationDelegate:class {
var operation:Optional<(MyOperation, didComplete:Bool) -> Void> { get }
}
class MyOperation {
weak var delegate:MyOperationDelegate?
func start() {
println("started")
self.delegate?.operation?(self, didComplete:true)
}
}
class Operator:MyOperationDelegate {
func doOperate() {
let operation = MyOperation()
operation.delegate = self
operation.start()
}
var operation:((MyOperation, didComplete:Bool) -> Void)? { return self._operation }
func _operation(operation:MyOperation, didComplete:Bool) {
println("operation: \(operation) didComplete:\(didComplete)")
}
}
let op = Operator()
op.doOperate()
and you cannot declare multiple similar delegate method names:
protocol MyOperationDelegate {
var operation:Optional<(MyOperation, didComplete:Bool) -> Void> { get }
var operation:Optional<(MyOperation, inProgress:) -> Void> { get }
// ^ [!] Invalid redeclaration of 'operation'
}
Upvotes: 6