Search code examples
swiftcoding-styleoption-typedefault-value

Confused about Optional vs Default value -1


We are working in a Swift project. A function was there like,

fun getSleepAmmount() -> Int {
    // calculate sleep time
    // return value when valid
    // else
    return -1
}

My team member prefers the above function where caller needs to check with -1 which is not I am comfortable with. My suggestion is to redesign with nil return (although callers still need to check nullability) like,

fun getSleepAmmount() -> Int? {
    // calculate sleep time
    // return value when valid
    // else
    return nil
}

But my colleagues do not want to redesign. Which version of the functions is cleaner and why?


Solution

  • Obviously, nil is much cleaner. Because of -1 means nothing. This is just a magic word. It is difficult to support, refactor and handle this case.