Skip to content

Instantly share code, notes, and snippets.

@NeoTeo
Created August 11, 2015 12:24
Show Gist options
  • Save NeoTeo/d3360f684414ba79ab32 to your computer and use it in GitHub Desktop.
Save NeoTeo/d3360f684414ba79ab32 to your computer and use it in GitHub Desktop.
Protocol type constraint issue
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()
@NeoTeo
Copy link
Author

NeoTeo commented Aug 11, 2015

In a Playground this errors on line 18 with a
Cannot invoke 'getId' with no arguments

@NeoTeo
Copy link
Author

NeoTeo commented Aug 11, 2015

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