cocoseis
cocoseis

Reputation: 1473

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?

Upvotes: 0

Views: 67

Answers (1)

Alexander
Alexander

Reputation: 63369

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(); inherited from Sprite
    // needs w(); inherited from Wable
}

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

class Pointer: Element, Wable  {
    // needs w(); inherited from Wable
    // needs e(); inherited from Element
}

protocol Wable {
    func W()
}

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

Upvotes: 1

Related Questions