I am writing an extension for Measurement in Swift. I see in Apple's documentation that the Measurement is declared as struct Measurement<UnitType> where UnitType : Unit.
I want to use UnitType as the argument type for my extension's function.
extension Measurement {
func quotient(as otherUnit: UnitType) -> Measurement {
return Measurement(value: floor(converted(to: otherUnit).value), unit: otherUnit)
}
}
This is an example of my function, but I am getting feedback saying...
Referencing instance method 'converted(to:)' on 'Measurement' requires that 'UnitType' inherit from 'Dimension'
How can I utilize UnitType generic the Measurement instance is already using?
CodePudding user response:
The generic placeholder UnitType is defined as being some kind of Unit. But there are many kinds of Unit. As the documentation says, it is only Units that are Dimension subclasses that permit a Measurement to be converted:
When a
Measurementcontains aDimensionunit, it gains the ability to convert between the kinds of units in that dimension.
So I would suggest you just do what the compiler says; reassure it that UnitType here does indeed inherit from Dimension:
extension Measurement where UnitType: Dimension {
// ^^^^^^^^^^^^^^^^^^^^^^^^^
func quotient(as otherUnit: UnitType) -> Measurement {
return Measurement(value: floor(converted(to: otherUnit).value), unit: otherUnit)
}
}
