Last active
June 27, 2018 02:19
-
-
Save jessesquires/4b6e76bb580600a85c40 to your computer and use it in GitHub Desktop.
Swift optional generic parameters?
This file contains 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
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) |
"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
Thanks guys!
So the full context is https://github.com/jessesquires/JSQDataSourcesKit.
Specifically: https://github.com/jessesquires/JSQDataSourcesKit/blob/develop/JSQDataSourcesKit/JSQDataSourcesKit/CollectionViewDataSourceProvider.swift#L34