swift - Comparing structs that conform to a protocol -
i have following structs represent point or line:
public struct point{ let x : double let y : double init (x : double, y : double) { self.x = x self.y = y } } extension point : equatable{} public func ==(lhs: point, rhs: point) -> bool { return lhs.x == rhs.x && lhs.y == rhs.y }
and
public struct line { let points : [point] init(points : [point]) { self.points = points } } extension line : equatable {} public func ==(lhs: line, rhs: line) -> bool { return lhs.points == rhs.points }
i want able have shape protocol or struct can use have points , lines , can compare between them. tried conforming protocol shape swift compiler gives me error when want compare point line though shapes.
do have move struct classes?
think may have use generics don't know how solve issue. in advance guidance.
edit1:
my approach shape protocol trying stuff nothing worked. tried following:
protocol mapshape : equatable { func == (lhs: mapshape, rhs: mapshape ) -> bool }
i changed code equatable extension lines given suggestion
this topic covered in wwdc 2015 session video protocol-oriented programming in swift, , here attempt apply situation:
you define protocol shape
, protocol extension method isequalto:
:
protocol shape { func isequalto(other: shape) -> bool } extension shape self : equatable { func isequalto(other: shape) -> bool { if let o = other as? self { return self == o } return false } }
isequalto:
checks if other element of same type (and compares them ==
in case), , returns false
if of different type.
all types equatable
automatically conform shape
, can set
extension point : shape { } extension line : shape { }
(of course can add other methods shape
should implemented shape types.)
now can define ==
shapes as
func ==(lhs: shape, rhs: shape) -> bool { return lhs.isequalto(rhs) }
and voilĂ , points , lines can compared:
let p1 = point(x: 1, y: 2) let p2 = point(x: 1, y: 3) let l1 = line(points: [p1, p2]) let l2 = line(points: [p1, p2]) print(p1 == p2) // false print(p1 == l1) // false print(l1 == l2) // true
remark: have ==
shape
type now, haven't figured out yet how make shape
conform equatable
. perhaps else can solve part (if possible).
Comments
Post a Comment