Last active
December 31, 2020 03:37
-
-
Save leodabus/a0e0a4f31f019b99e5f2026c5b17cc5c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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