Search code examples
swiftvariablessubtraction

How to get only positive value while subtracting in swift?


I want to get the value of zero while the larger value is subtracted from the smaller one. For eg:

var a = 10
var b = 3
var c = b-a

and it should print c = 0 instead of c = -8


Solution

  • You can use max(b-a, 0), which will return b-a in case the result is positive and 0 otherwise.

    let a = 10
    let b = 3
    let c = max(b-a,0)