Skip to content

Instantly share code, notes, and snippets.

@leodabus
Last active December 31, 2020 03:37
Show Gist options
  • Save leodabus/a0e0a4f31f019b99e5f2026c5b17cc5c to your computer and use it in GitHub Desktop.
Save leodabus/a0e0a4f31f019b99e5f2026c5b17cc5c to your computer and use it in GitHub Desktop.
extension FixedWidthInteger where Self: SignedInteger {
func roundedUpDivision(by divisor: Self) throws -> Self {
guard divisor != .zero else {
throw Division.Error.divideByZero
}
guard !(self == .min && divisor == -1) else {
throw Division.Error.overflow
}
let roundedTowardsZeroQuotient = self / divisor
if isMultiple(of: divisor) { return roundedTowardsZeroQuotient }
return (divisor > .zero) == (self > .zero) ?
roundedTowardsZeroQuotient + 1 :
roundedTowardsZeroQuotient
}
}
struct Division {
enum Error: Swift.Error {
case divideByZero
case overflow
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment