Created
August 11, 2015 12:24
-
-
Save NeoTeo/d3360f684414ba79ab32 to your computer and use it in GitHub Desktop.
Protocol type constraint issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
protocol ThingId { } | |
protocol Thing { | |
func getId<A: ThingId>() -> A | |
} | |
struct MyThingId: ThingId { } | |
struct MyThing: Thing { | |
func getId<A: ThingId>() -> A { | |
return (MyThingId() as? A)! | |
} | |
} | |
let aThing = MyThing() | |
aThing.getId() |
I'm not sure if I'm just using generics wrong with protocols but it seems inconsistent that Swift uses type parameters in classes/structs and associated types in protocols for what amounts to the same thing – allowing to defer the definition of the type. This different version works as I intended the above to work:
import Cocoa
protocol ThingId { }
protocol Thing {
typealias IdType
func getId() -> IdType
}
struct MyThingId: ThingId { }
struct MyThing: Thing {
typealias IdType = MyThingId
func getId() -> MyThingId {
return MyThingId()
}
}
let aThing = MyThing()
aThing.getId()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In a Playground this errors on line 18 with a
Cannot invoke 'getId' with no arguments