Skip to content

Instantly share code, notes, and snippets.

@jessesquires
Last active June 27, 2018 02:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jessesquires/4b6e76bb580600a85c40 to your computer and use it in GitHub Desktop.
Save jessesquires/4b6e76bb580600a85c40 to your computer and use it in GitHub Desktop.
Swift optional generic parameters?
protocol FactoryAType {
typealias Product
}
protocol FactoryBType {
typealias Product
}
struct CombinedFactory<T: FactoryAType, U: FactoryBType where T.Product == U.Product> {
let factoryA: T
let factoryB: U?
init(factoryA: T, factoryB: U? = nil) {
self.factoryA = factoryA
self.factoryB = factoryB
}
}
struct IntAFactory: FactoryAType {
typealias Product = Int
}
struct IntBFactory: FactoryBType {
typealias Product = Int
}
let fa = IntAFactory()
let fb = IntBFactory()
let allGood = CombinedFactory(factoryA: fa, factoryB: fb)
// Does not work:
// Cannot invoke initializer for type 'CombinedFactory<_, _>' with an argument list of type '(factoryA: IntAFactory)'
let combinedFactory = CombinedFactory(factoryA: fa)
// This works:
// But this is awkward. I don't want to have to specify B if it is nil
let workingFactory = CombinedFactory<IntAFactory, IntBFactory>(factoryA: fa)
@rnapier
Copy link

rnapier commented Nov 7, 2015

@jessesquires
Copy link
Author

"Factory" is already sounding like something un-Swifty.

Ha -- probably because I'm trying to make Cocoa less cubersome. I hate that UICollectionView/UITableView delegates/dataSources are littered with @optional methods 😢

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