Last active
November 29, 2023 11:01
-
-
Save SoundBlaster/3568ec85be4342382e76378d62e4e28e to your computer and use it in GitHub Desktop.
Swift Generic constrained by Protocol
This file contains hidden or 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
// 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