My divide function from yesterday has a flaw.
func divide(_ a:Int, by b:Int)->(quotient:Int, remainder:Int) {
let quotient:Int = a/b
let remainder = a - quotient * b
return (quotient, remainder)
}
When
b
is
0
, it crashes. Re-write the function to use a guard for a non-0
b
and change the return type to make the whole tuple optional. Now adjust your calling code. Test it to make sure it works.
Solution
func divide(_ a:Int, by b:Int)->(quotient:Int, remainder:Int)? {
guard b != 0 else { return nil }
let quotient:Int = a/b
let remainder = a - quotient * b
return (quotient, remainder)
}
Whenever doing integer division in Swift, remember that division by 0 crashes your entire app. Guard against it.
Comments for Guarding Against Crashes