0

This is what I've tried and can't figure out where the error is coming from. Is there something missing? Syntax error? I tried doing similar with if-else in the function and also getting errors.

var steps = 0

func incrementSteps() -> Int {
    steps += 1
    print(steps)
    return steps
}

incrementSteps()
let goal = 10000
func progressUpdate() -> Int {
    let updated = progressUpdate()/goal
    switch updated {
    case (0.0..<0.1):
        print("Great start")
    case (0.11..<0.5):
        print("Almost halfway")
    case (0.51..<0.9):
        print("Almost complete")
    default:
        print("Beat goal")
    }
}
progressUpdate()
aberg619
  • 11
  • 2
  • See https://stackoverflow.com/questions/31411336/integer-division-int-is-not-convertible-to-double or other questions about integer division in Swift. – Martin R Jun 05 '20 at 16:39
  • 2
    Why does `progressUpdate()` call itself recursively? – Martin R Jun 05 '20 at 16:40

1 Answers1

0

You need to specify updated as Double. And cast it back to Int when returning(if you require Int for your requirement).

Note: Also, you need to modify calling the progressUpdate function within progressUpdate definition which causes a recursion. If you want to do so you might want to give condition to break the loop.

func progressUpdate() -> Int {
    let updated = Double(steps/goal)
    switch updated {
    case (0.0..<0.1):
        print("Great start")
    case (0.11..<0.5):
        print("Almost halfway")
    case (0.51..<0.9):
        print("Almost complete")
    default:
        print("Beat goal")
    }
    return Int(updated)
}
Frankenstein
  • 15,732
  • 4
  • 22
  • 47
  • 1
    That would do a (truncating) integer division and convert the result to a Double. While it may fix the compiler error, it probably does not give the intended result. – Martin R Jun 05 '20 at 16:38
  • after making the suggested adjustment, error "All paths through this function will call itself" is now present on the function line and "Missing return in a function expected to return 'Int'" on the call line. – aberg619 Jun 05 '20 at 16:52
  • You're not returning anything in the question. What exactly are you trying to return? Add that to your code. Also, calling the same function when entering the function is a bad practice. You might want to provide a while condition to break the execution. – Frankenstein Jun 05 '20 at 16:58
  • @aberg619 `let percentage = Double(steps)/goal` and then switch percentage. – Leo Dabus Jun 05 '20 at 17:00
  • @aberg619 If goal is an integer you would need to to coerce it to Double as well – Leo Dabus Jun 05 '20 at 17:22
  • Thank you for all the great advice!! Just learning so my tool box is limited. – aberg619 Jun 05 '20 at 17:35