Skip to content

Instantly share code, notes, and snippets.

@SoundBlaster
Last active November 29, 2023 11:01
Show Gist options
  • Save SoundBlaster/3568ec85be4342382e76378d62e4e28e to your computer and use it in GitHub Desktop.
Save SoundBlaster/3568ec85be4342382e76378d62e4e28e to your computer and use it in GitHub Desktop.
Swift Generic constrained by Protocol
// protocols
protocol Connection {
init()
}
protocol Factory<T> {
associatedtype T: Connection
func create() -> T
}
// implementation
class RealConnection: Connection {
required init() {
}
}
class RealFactory<T>: Factory where T: Connection {
func create() -> T {
T.init()
}
}
// usage
let factory = RealFactory<RealConnection>()
let connection = factory.create()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment