cocoseis cocoseis - 5 months ago 10
Swift Question

Inheriting from multiple classes which have the same super class - workaround

Following situation:

class Sprite{ // has to be a class, not a protocol!
func s(); // can not be changed
}
class Element: Sprite{
// needs s(); for:
func e();
}
class Wiggle: Sprite{
// needs s(); for:
func w();
}


How could I achieve something like:

class Button: Wiggle{
// needs s();
// needs w();
}
class Cursor: Element, Wiggle{
// needs s();
// needs w();
// needs e();
}
class Pointer: Element{
// needs w();
// needs e();
}


This is not working since for Cursor Wiggle and Element both inherit from Sprite.

Hence I was thinking about using an extension approach like:

class Button:Sprite{
// needs s();
// needs w();
}
class Cursor: Element{
// needs s();
// needs w();
// needs e();
}
class Pointer: Element{
// needs w();
// needs e();
}

extension Button, Cursor { // or similar to make w() available in Button & Cursor
// using s() for:
// func w();
}


How can I extend
Button
&
Cursor
in one single step?

Answer

You can put your w() in its own protocol, e.g. Wable, to which Button and Cursor conform. Give Wable a default implementation for w(). Because w() depends on s(), you must impose a constraint on the extension such that only it only applies to conforming types deriving from Sprite (the "source" of s()).

class Button: Sprite, Wable {
    // needs s();
    // needs w();
}

class Cursor: Element, Wable {
    // needs s();
    // needs w();
    // needs e();
}

class Pointer: Element {
    // needs w();
    // needs e();
}

protocol Wable {
    func W()
}

extension Wable where Self : Sprite {
    func W() {
        print("foo")
    }
}
Comments