cocoa - Swift protocol similar to Equatable -


i’m trying create protocol types lerp-able (linear-interpolatable). i’m declaring how equatable defined:

protocol lerpable {     func lerp(from: self, to: self, alpha: double) -> self } 

unfortunately, when try implement lerpable double:

func lerp(from: double, to: double, alpha: double) -> double {     return + alpha * (to - from) } extension double: lerpable {} 

i error: type 'double' not conform protocol 'lerpable'.

i assumed pretty straightforward, maybe don’t understand how equatable works. or special case in swift? thoughts?


update: correct answer below, , here’s final version of code, others’ reference:

protocol lerpable {     func lerp(to: self, alpha: double) -> self }  extension double: lerpable {     func lerp(to: double, alpha: double) -> double {         return self + alpha * (to - self)     } }  func lerp<t: lerpable>(from: t, to: t, alpha: double) -> t {     return from.lerp(to, alpha: alpha) } 

i added global lerp function still refer as
lerp(foo, bar, alpha: 0.5)
rather than
foo.lerp(bar, alpha: 0.5)

to fix problem need put lerp function inside extension, so:

extension double: lerpable {     func lerp(from: double, to: double, alpha: double) -> double {         return + alpha * (to - from)     } } 

if have @ equatable protocol:

protocol equatable {     func == (lhs: self, rhs: self) -> bool } 

the reason declare method (== specifically) outside type extension because equatable wants overload operator , operators must declared @ global scope. here's example clarify:

protocol myprotocol {     func *** (lhs: self, rhs: self) -> self } 

now make int adopt protocol:

extension int : myprotocol {}  infix operator *** {} func *** (lhs: int, rhs: int) -> int {     return lhs * rhs } 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -