Function that accepts any type of Measurement in swift

You can make the function generic

func formatMeasurementAsString<T: Unit>(measurement: Measurement<T>) -> String {
    return "\(Int(measurement.value)) \(measurement.unit.symbol)"


let length = Measurement(value: 180.0, unit: UnitLength.meters)
let speed = Measurement(value: 60, unit: UnitSpeed.kilometersPerHour)

print(formatMeasurementAsString(measurement: length))
print(formatMeasurementAsString(measurement: speed))

180 m
60 km/h

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top