Skip to content

Instantly share code, notes, and snippets.

@troystribling
Last active April 28, 2022 20:55
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save troystribling/26cf6a0510454eda1af0 to your computer and use it in GitHub Desktop.
Save troystribling/26cf6a0510454eda1af0 to your computer and use it in GitHub Desktop.
A swift protocol with associated type used as type parameter in generic function
protocol Thing {
typealias argType
func doit(val:argType) -> argType
}
class IntThing : Thing {
func doit(val: Int) -> Int {
return val + 1
}
}
func doThing<A:Thing>(thing:A, val:A.argType) -> A.argType {
return thing.doit(val)
}
doThing(IntThing(), 2)
@crsantos
Copy link

Update for Swift3:

protocol Thing {
    associatedtype argType
    func doit(_ val:argType) -> argType
}

class IntThing : Thing {
    typealias argType = Int
    func doit(_ val: Int) -> Int {
        return val + 1
    }
}

func doThing<A:Thing>(_ thing: A, _ val: A.argType) -> A.argType {
    return thing.doit(val)
}

doThing(IntThing(), 2)

@pejalo
Copy link

pejalo commented Mar 22, 2018

How would you declare a delegate property of type Thing?

weak var delegate: Thing? would produce Xcode error:
Protocol 'Thing' can only be used as a generic constraint because it has Self or associated type requirements

@ankits16
Copy link

@pejalo did you find the answer?

@sevenday83
Copy link

@pejalo, @ankits16 you should look Type Erasure to achieve this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment