Grant Emerson

Greatest or Biggest

Greatest or Biggest — SwiftMoji Entry #21

Swift provides a convenient static method on Double called maximumMagnitude(_:_:). It has two Double parameters labeled x and y. Instead of simply returning the greatest, it compares the magnitude property of both Doubles to obtain the one with the greatest absolute value. In the code example, the reduce function is used with an initial value of 0 and maximumMagnitude as the combining method to extract the maximum velocity from an Array of Doubles.

let 🚀Velocities = [700.55, 500.3, 1015.0, -50.0, -2000.25]
let maxVelocity = 🚀Velocities.reduce(0, Double.maximumMagnitude)
print("\(maxVelocity) mph") // -2000.25 mph
Tagged with: