Search code examples
swiftreturn

missing return in a function expected to return 'Double' | What to do?


Following code:

protocol ExampleProtocol {
    var simpleDescription: String { get }
    var absoluteValue: Double { get }
    mutating func adjust()
}

extension Double: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    var absoluteValue: Double {
        if self < 0 {
            return self * -1
        } else if self > 0 {
            return self
        }
    }
    mutating func adjust() {
        self += 42
    }
}

When trying to execute it with either simpleDescription or absoluteValue (e.g. print(10.simpleDescription), I just get this error:

missing return in a function expected to return 'Double'

The absoluteValue "function" returns itself, so the Double value, so why is it saying it's missing one?


Solution

  • The issue is that your if statement is missing an else block, the return value is not defined for the case when self == 0. You can simply change the else if branch to else, because you also want to return self for 0.

    var absoluteValue: Double {
        if self < 0 {
            return self * -1
        } else {
            return self
        }
    }
    

    You can also write this as a oneliner using the ternary operator:

    var absoluteValue: Double {
        return self < 0 ? self * -1 : self
    }