Swift 协议:向实例添加协议一致性
Swift Protocols: Adding Protocol conformance to an Instance
我正在尝试了解如何在实例具有特定值的情况下向该实例添加协议一致性。这是我试图理解的 "stupid" 示例。
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 {}
}
}
}
我提出另一种方法
您可以使用工厂方法:
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 { }
截至 "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.
因此您无法将协议一致性添加到特定实例。
我正在尝试了解如何在实例具有特定值的情况下向该实例添加协议一致性。这是我试图理解的 "stupid" 示例。
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 {}
}
}
}
我提出另一种方法
您可以使用工厂方法:
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 { }
截至 "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.
因此您无法将协议一致性添加到特定实例。