Search code examples
iosswiftswitch-statementuipickerview

Cannot convert return expression of type 'CountableClosedRange<Int>' to return type 'Int?' in Switch-case


I am trying to return ranges of values when the user select from pickerview. I used switch-case statements. My question is about, how to return ranges of values in return statement?

Here is my code. It is not correct since I got this error, Cannot convert return expression of type 'CountableClosedRange' to return type 'Int?'

  private func price(from string: String) -> Int? {
    switch string {
    case "less than 100":
        return 0 ... 100 // the error is here
    case "500-100":
        return 100 ... 500
    case "1000-500":
        return 500 ... 1000
    case "3000-1000":
        return 1000 ... 3000
    case "5000-3000":
        return 3000 ... 5000
    case "larger than 5000":
        return (I don't know)
    case _:
        return nil
    }
}

Solution

  • I don't understand what sense your switch cases are supposed to make, but this, though conceptually nonsensical in my opinion, at least will compile:

    private func price(from string: String) -> CountableClosedRange<Int>? {
        switch string {
        case "less than 100":
            return 0 ... 100 // the error is here
        case "500-100":
            return 100 ... 500
        case "1000-500":
            return 500 ... 1000
        case "3000-1000":
            return 1000 ... 3000
        case "5000-3000":
            return 3000 ... 5000
        case "larger than 5000":
            return 5000 ... Int.max
        case _:
            return nil
        }
    }