Swift, implement same delegate two times (without multicast) [duplicate] - swift

This question already has answers here:
In Swift, how do I have a UIScrollView subclass that has an internal and external delegate?
(4 answers)
Closed 4 years ago.
Given a very simple protocol :
protocol TheProtocol {
func doSomething()
func doSomethingElse()
func doThis()
func doThat()
}
I have a class Base that has a delegate waiting to be set.
// Can't modify this class at all
class Base {
public var delegate: TheProtocol?
}
My second class B inherits from this class Base, and implements TheProtocol in order to set the delegate to itself.
class B: Base, TheProtocol {
override init() {
super.init()
self.delegate = self
}
func doSomething() {
}
func doSomethingElse() {
}
... other methods to implement
}
Now what I want to be able to do, is to have a last class C, that contains an instance of B, and also set the delegate. I want the delegate to work both inside B and C.
The major constraint is that I can't modify the Base class.
class C: TheProtocol {
var obj = B()
init() {
// If I do this it won't fire within B anymore
obj.delegate = self
}
func doSomething() {
}
func doSomethingElse() {
}
... other methods to implement
}

It is actually possible using a Proxy delegate. However not really recommended.
In Swift, how do I have a UIScrollView subclass that has an internal and external delegate?

Related

Best approach for reusable swift code UIKit

I cannot see a practical approach for reusable storyboard patterns in Xcode/Swift. I have a number of ViewControllers which have almost identical behavior and appearance. So the viewDidLoad() is always the same:
override func viewDidLoad() {
super.viewDidLoad()
labelKESumme.text = something
}
Because each ViewController has to be configured with its own class and Swift lacks multi inheritance I've tried to create an extension like this:
extension UIViewController {
func show() {
self.labelKESumme.text = something <== ... has no member
}
}
But that doesn't work due to 'has no member' errors. Also it's not possible to configure outlets between the label and the extension code. Need an approach for configure many view controllers with same content without code duplication.
You can use protocol extensions like below
// protocol
protocol Showable {
var labelKESumme: UILabel?
func show()
}
//protocol extension if you want same functionality everywhere
extension Showable {
func show() {
labelKESumme?.text = something
}
}
// just conform the the protocol
ABCViewController: Showable {
}
// just conform the the protocol
XYZViewController: Showable {
}
// In some code where you have viewController as UIViewController and you know
// that this object conforms to Showable protocol then you can do like this
guard let showable = viewController as? Showable {
return
}
showable.show()

How to class the superclass of a superclass in Swift?

ArtistVC is a subclass of CategoryVC which is a subclass of BrowserVC.
Most of ArtistVC's UITableView Data Source methods wind up calling CategoryVC's implementation of those methods with return super.tableView(tableView, cellForRowAt: adjustedIndexPath)(for example), after some other things happen of course, like modifying the indexPath passed to the method.
But sometimes I actually want to bypass CategoryVC's implementation and use BrowserVC's implementation.
super.super.someMethod() apparently isn't the answer. Is this possible?
There's a (convoluted) way to do this but it requires that the intermediate class "contributes" to the bypassing of its override.
For example:
class A
{
func doIt(_ parameter:Int) { print("A.doIt(\(parameter))") }
}
class B:A
{
override func doIt(_ parameter:Int) { print("B.doIt(\(parameter))") }
var super_doIt:(Int)->() { return super.doIt }
}
class C:B
{
override func doIt(_ parameter:Int)
{ super.super_doIt(parameter) }
}
let c = C()
c.doIt(3) // A.doIt(3)

Swift: overriding typealias inside subclass

So I was thinking about a custom pattern in my project, but I can't get it to work. The main idea is to change the typealias on every subclass to get access to the subclass specific interface.
protocol InstanceInterface: class {
typealias Interface
var interface: Interface { get }
}
// Baseclass
protocol FirstClassInterface: class { /* nothing here for the example */ }
class FirstClass: InstanceInterface, FirstClassInterface {
typealias Interface = FirstClassInterface
var interface: Interface { return self }
}
// Subclass
protocol SecondClassInterface: FirstClassInterface {
func foo()
}
class SecondClass: FirstClass, SecondClassInterface {
typealias Interface = SecondClassInterface // <--- This does nothing :(
func foo() { print("hello world") } // Swift 2.0 here
}
// Lets say I want to call foo trough the interface
let test = SecondClass()
test.interface.foo() // 'Interface' does not have a member named 'foo'
Is there something I'm doing wrong or do I misunderstand some Swift concepts here?! I do need to subclass here to not to implement everything from super class' protocols over and over again. Is my little pattern even possible? I'd appreciate any help. :)
Would something like this work for your purposes?
class MyClass<T> {
}
class MySubclass1: MyClass<String> {
}
class MySubclass2: MyClass<Int> {
}
Unfortunately there is no good workaround for this problem.
The main idea to override the typealias would work in this case but consider the following:
protocol TakeAndGet {
typealias T
func take(value: T)
func get() -> T
}
class FirstClass: TakeAndGet {
typealias T = FirstClass
var property = 0
func take(value: T) {
value.property = 4
}
func get() -> T {
return FirstClass()
}
}
class SecondClass: FirstClass {
typealias T = SecondClass
var property2 = "hello"
}
If the typealias of the SecondClass overrides the other one the take method would work since it takes a subclass which can be treated as the superclass. But the get method cannot implicitly convert FirstClass to SecondClass. Therefore it is not possible to override a typealias.
Now if we want to override the get function with get() -> SecondClass it wouldn't work since it has not the same signature as the one in the superclass. In addition we inherit the get method which results in an ambiguous use:
SecondClass().get() // which type gets returned? SecondClass or FirstClass
So you have to try a different approach.

How to tell if a subclass overrides a method in Swift

I’ve got a Swift class Parent that has a method doSomething() and I want to detect (in Parent) if a subclass has overridden doSomething(). How do I do that?
class Parent {
func doSomething() {}
func subclassOverridesDoSomething() -> Bool {
// what goes here?
return true
}
}
class Child: Parent {
override func doSomething() {}
}
I know I can do this with NSObject or even the Objective C runtime functions, but how can I do it with Swift classes?
You can use the Objective-C runtime provided you expose the function with dynamic:
class Parent {
func doSomething() {}
func subclassOverridesDoSomething(t:Parent.Type) -> Bool {
let originalMethod = class_getInstanceMethod(t, "doSomething")
return originalMethod != nil
}
}
class Child: Parent {
dynamic override func doSomething() {}
}
Parent().subclassOverridesDoSomething(Child.self)
If you omit dynamic, it won't work because Objective-C can't see the method.
Well Swift doesn't really offer methods to do that.
Also in my opinion, there is no disadvantage in using Objective-c methods like method_getImplementation or the NSObject. You will have to use the methods objective-c offers you to solve your problem.
For example:
let selector = Selector("viewWillAppear:")
let originalMethod = class_getInstanceMethod(YourClass, selector)

Swift implement multiple protocols with a delegate

I'm trying to implement a protocol that itself inherits multiple protocols that both have a delegate member. Is there a clean way to do this without needing different names for the delegate of each protocol?
protocol ProtocolOne {
var delegate: ProtocolOneDelegate?
}
protocol ProtocolTwo {
var delegate: ProtocolTwoDelegate?
}
protocol CombinedProtocol: ProtocolOne, ProtocolTwo {
}
protocol CombinedDelegate: ProtocolOneDelegate, ProtocolTwoDelegte {
}
class ProtocolImpl: CombinedProtocol {
// How can I implement delegate here?
// I've tried the following options without success:
var delegate: CombinedDelegate?
var delegate: protocol<ProtocolOneDelegate, ProtocolTwoDelegate>?
}
You should be able to combine them in one:
var delegate: (ProtocolOneDelegate & ProtocolTwoDelegate)?
You can now use both protocols.
In your code, delegate is just a normal property. You can have multiple protocols declaring a property with the same name and same type, and have a class directly or indirectly implement it.
If different protocols define a property with the same name but different type, you won't be able to make it compile, because the compiler will complain for redeclaration of a property and class not confirming to one of the protocols.
There are 2 possible solution. The most obvious one is to avoid using names having high probability of being used in other protocols - delegate is a typical case. Use a different naming convention, such as protocol1Delegate, dataSourceDelegate, apiCallDelegate, etc.
The 2nd solution consists of replacing properties with methods. For example:
protocol P1 {
func test() -> String?
}
protocol P2 {
func test() -> Int?
}
protocol P3: P1, P2 {
}
class Test : P3 {
func test() -> String? { return nil }
func test() -> Int? { return nil }
}
Swift consider functions with the same parameters list but different return type as overloads. Note however that if 2 protocols use the same function signature (name, parameters and return type), when implementing in the class you will implement that function once - that might be the wanted behavior in some cases, but unwanted in other cases.
A solution might be to use protocol extensions (check extension Combined). The benefit is that Combined only declares delegate and oneDelegate and twoDelegate are computed cross-implementation. Unfortunately, it's a requirement to have the three variables exposed out of the class, that might be inconvenient.
// MARK: - Delegates protocols
protocol OneDelegate {
func oneDelegate(one: One)
}
protocol TwoDelegate {
func twoDelegate(two: Two)
}
protocol CombinedDelegate: OneDelegate, TwoDelegate {
func combinedDelegate(combined: Combined)
}
// MARK: - Model protocols
protocol One: class {
var oneDelegate: OneDelegate? { get }
}
protocol Two: class {
var twoDelegate: TwoDelegate? { get }
}
protocol Combined: One, Two {
var delegate: CombinedDelegate? { get }
}
extension Combined {
var oneDelegate: OneDelegate? {
return delegate
}
var twoDelegate: TwoDelegate? {
return delegate
}
}
// MARK: - Implementations
class Delegate: CombinedDelegate {
func oneDelegate(one: One) {
print("oneDelegate")
}
func twoDelegate(two: Two) {
print("twoDelegate")
}
func combinedDelegate(combined: Combined) {
print("combinedDelegate")
}
}
class CombinedImpl: Combined {
var delegate: CombinedDelegate?
func one() {
delegate?.oneDelegate(self)
}
func two() {
delegate?.twoDelegate(self)
}
func combined() {
delegate?.combinedDelegate(self)
}
}
// MARK: - Usage example
let delegate = Delegate()
let protocolImpl = CombinedImpl()
protocolImpl.delegate = delegate
protocolImpl.one()
protocolImpl.two()
protocolImpl.combined()