Last active
March 11, 2022 22:23
-
-
Save matt-curtis/65eb4bd7e98e6ace2d220c3067df7fc7 to your computer and use it in GitHub Desktop.
Delegate Forwarding in Swift. Useful for choosing some methods of a delegate to handle yourself and others to pass to a different delegate. Inspired by WebKit's Objective-C implementation of the same for UIScrollViewDelegate: https://github.com/WebKit/WebKit/blob/20586209d4e623ecaf489c9913a5732d80ba6e39/Source/WebKit/UIProcess/ios/WKScrollView.m…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DelegateForwarder<T: NSObjectProtocol>: NSObject { | |
// MARK: - Properties | |
weak var internalDelegate: T? | |
weak var externalDelegate: T? | |
var asConforming: T { | |
return unsafeBitCast(self, to: T.self) | |
} | |
// MARK: - Init | |
init(internalDelegate: T? = nil, externalDelegate: T? = nil) { | |
self.internalDelegate = internalDelegate | |
self.externalDelegate = externalDelegate | |
} | |
// MARK: - Forwarding | |
override func responds(to sel: Selector!) -> Bool { | |
return | |
self.internalDelegate?.responds(to: sel) ?? false || | |
self.externalDelegate?.responds(to: sel) ?? false | |
} | |
override func forwardingTarget(for sel: Selector!) -> Any? { | |
if self.internalDelegate?.responds(to: sel) == true { | |
return self.internalDelegate | |
} | |
return self.externalDelegate | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment