Hey everyone, how're things going?
In our app, we have a canvas. The canvas could contain Stickers, Images, Texts, etc. We have a protocol CanvasItem
that implement the common properties between these items:
public protocol CanvasItem: AnyObject {
var scale: CGFloat { get set }
var rotation: CGFloat { get set }
var alpha: CGFloat { get set }
var zIndex: Int { get }
}
Then each class-model (Stickers, Text etc) conform to CanvasItem
, adding class-specific properties:
public class StickerItem: CanvasItem {
public var stickerName: String
}
public class ShapeItem: CanvasItem {
public var shapeColor: UIColor
}
To show those, we first created a base generic (I think) UIView
class that can be inited only with CanvasItem
:
class ViewClass<T: CanvasItem>: UIView {
let canvasItem: T
init (t: T) {
self.canvasItem = t
super .init(frame: .zero)
}
}
and then for each of the models, we create specific UIView<CanvasItem>
class:
class CanvasShapeView: ViewClass<ShapeItem> {
}
class CanvasStickerView: ViewClass<StickerItem> {
}
Then I'm trying to do the following:
let superview = UIView()
let shapeView = CanvasShapeView<ShapeItem>(t: <ShapeItem>)
let stickerView = CanvasStickerView<StickerItem>(t: <StickerItem>)
superview.addSubview(shapeView)
superview.addSubview(stickerView)
for canvasItemView in superview.subviews.compactMap({$0 as ? ViewClass<CanvasItem>}) {
print(canvasItemView.canvasItem) // **access only the common properties**
}
I'm trying to access only to the CanvasItem
common properties but it doesn't let me, throwing a compile error:
Protocol type 'CanvasItem' cannot conform to 'CanvasItem' because only concrete types can conform to protocols
Any suggestions? We stuck on this for a few good days now ah.
Any help would be highly appreciated.