user4956851
user4956851

Reputation:

Swift Protocols: Adding Protocol conformance to an Instance

I'm trying to understand how to add a protocol conformance to an instance if the instance has a particular value. This is a "stupid" example of what I'm trying to understand.

enum TypeOfFigure {
  case square, circle, triangle
}

protocol Figure {
    var type: TypeOfFigure { get }
}
protocol Square {}
protocol Circle {}
protocol Triangle {}


class FigureType: Figure {
    let type: TypeOfFigure

    init (type: TypeOfFigure) {
        self.type = type
        switch type {
        case .square: //extension self: Square {}
        case .circle: //extension self: Circle {}
        case .triangle: //extension self: Triangle {}
        }
    }

}

Upvotes: 0

Views: 272

Answers (2)

francybiga
francybiga

Reputation: 1138

As of "The Swift Programming Language":

The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

Thus you can't add protocol conformance to a specific instance.

Upvotes: 1

Marco Santarossa
Marco Santarossa

Reputation: 4066

I propose an alternative approach

You can use a factory method:

class FigureTypeFactory {
    static func createFigure(withType type: TypeOfFigure) -> Figure {
        switch type {
            case .square: return new FigureSquare()
            case .circle: return new FigureCircle()
            case .triangle: return new FigureTriangle()
        }
    }
}

class Figure { }

class FigureSquare: Figure, Square { }

Upvotes: 4

Related Questions