Swift supply generic method type parameter when implementing protocol method -
i have protocol called contentservice intended expose common functionality reading data various rest apis. each implementation of contentservice perform mechanics required particular api.
protocol contentservice { func loadnextpage<t>(pagestartid: t) -> [datum] //other methods... }
since given api may have different way of marking page boundaries of returned data, want specify required type in implementing class follows:
class servicea : contentservice { func loadnextpage<int>(pagestartid: int) -> [datum] { //do pagestartid typed int return posts } } class serviceb : contentservice { func loadnextpage<nsdate>(pagestartid: nsdate) -> [datum] { //do pagestartid typed nsdate return posts } }
note i'm specifying type parameter in definition of implementing types (servicea, serviceb) because specific service. expectation instance of these classes have method signature loadnextpage(pagestartid: x) -> [post]
x specific type supplied t when implementing method.
in order load page of data api, therefore use this:
let apia = servicea() let apib = serviceb() let dataa = apia.loadnextpage(1234) let datab = apib.loadnextpage(nsdate())
while compiles without errors. can compile following without errors:
let dataa = apia.loadnextpage("anything works here.")
therefore, servicea's loadnextpage() method isn't being restricted int parameters. furthermore, in method definitions loadnextpage() method, although pagestartid parameter seems of expected type when inspecting in xcode, can't use operators or methods accessible on type. example, in servicea's implementation can't let newid = pagestartid + 5
though pagestartid should int.
two questions:
1) i'm misunderstanding generic methods in swift , know why pattern can't used.
2) if has clever solution achieve want i'm trying above, i'd love know it.
your protocol
protocol contentservice { func loadnextpage<t>(pagestartid: t) -> [datum] //other methods... }
requires generic method loadnextpage
, and
func loadnextpage<int>(pagestartid: int) -> [datum] { //do pagestartid typed int return posts }
is that: generic method placeholder happens have name int
. inside method, int
refers placeholder type , hides global swift type int
. equivalent definition be
func loadnextpage<foo>(pagestartid: foo) -> [datum] { //do pagestartid typed int return posts }
what want define protocol associated type t
:
protocol contentservice { associatedtype t func loadnextpage(pagestartid: t) -> [datum] //other methods... }
and class adopts protocol t == int
:
class servicea : contentservice { func loadnextpage(pagestartid: int) -> [datum] { let newid = pagestartid + 5 // <-- compiles now! //do pagestartid typed int return posts } }
now
let dataa = apia.loadnextpage(1234)
compiles, but
let dataa2 = apia.loadnextpage("anything works here.") // error: cannot convert value of type 'string' expected argument type 'int'
doesn't, expected.
Comments
Post a Comment