I have a question about Swift generic types
I want to make a Mapping protocol to convert one class object of another class object.
To do that I declare the protocol:
protocol Mapping {
associatedtype T
associatedtype R
mutating func map(obj: T) -> R
}
Now, with the using of Mapping, I want to calculate how many users have paid me.
I am implementing a Calculator which should be able to convert User to Double
class Calculator<Model> {
private let objects: [Model]
private var mapping: Mapping // My trouble: I need Mapping<User,Double>
init(objects: [Model], mapping: Mapping /* I need Mapping<User,Double> */) {
self.objects = objects
self.mapping = mapping
}
func calculate() {
let numbers = self.objects.map { (obj: Model) -> Double in
return self.mapping.map(obj)
}
// ... sum for numbers
}
}
I want the Mapping protocol to be able to make several implementations of it, for example, ClosureMapping.
How do I declare that I need Mapping with specific classes for T and R?
I can use generic for Mapping
class Calculator<CalcMapping: Mapping, Model> where CalcMapping.T == Model, CalcMapping.R == Double {
private let objects: [Model]
private var mapping: CalcMapping
init(objects: [Model], mapping: CalcMapping) {
self.objects = objects
self.mapping = mapping
}
func calculate() {
let numbers = self.objects.map { (obj: Model) -> Double in
return self.mapping.map(obj)
}
// ... sum for numbers
}
}
but so I can’t change the mapping strategy. I always need to specify a specific mapping strategy in declaring a variable
class Manager {
private let calculator: Calculator<MyMapping, User>
func init() {
let users = [User]() // ...
self.calculator = Calculator(objects: users, mapping: MyMapping)
// I can't create calculator with another Mapping, eg MappingMock
}
}
Update
I was able to specify protocol requirements with associative types through the use of an abstract class. I have two variables that are declared the same, but I use different mapping implementations.
let yearPurchaseMapping = UserClosureMapping { (user: User) -> Double in
user.yearPurchases()
}
let monthPurchaseMapping = UserMonthPurchaseMapping()
let yearCalc: Calculator<AbstractMapping<User,Double>, User, Double> = Calculator(mapping: yearPurchaseMapping)
let monthCalc: Calculator<AbstractMapping<User,Double>, User, Double> = Calculator(mapping: monthPurchaseMapping)
my gist https://gist.github.com/chchrn/0eff4681bf1f9f5312ce7b862c168cc8
Swift
. You can only use such protocol in your generic type similar toCalculator
where associated type are defined and understood by the compiler. In any concrete declaration where associated types are not known, compiler won't allow that.Calculator
whereModel == User
, but I need use various Classes implemented Mapping with specific associated typesT=User, R =Double
.Mapping
is a Strategy for converting aUser
->Double
. And I want to specify only conditions for associated types in Calculator,T == User, R == Double