Hi guys,
I am new around here and just picking up the basics (of programming in general). I am working through the "App Development with Swift" course that Apple provides for free.
I am going though "functions" and came across an exercises that I am having trouble understaging - see the function below ->
let goal = 10000
var steps = 15
func progressUpdate() {
if steps < Int(Double(goal)*0.1) {
print("You're off to a good start.")
} else if steps < goal/2 {
print("You're almost halfway there!")
} else if steps < Int(Double(goal)*0.9) {
print("You're over halfway there!")
} else if steps < goal {
print("You're almost there!")
} else {
print("You beat your goal!")
}
}
I get the function and what it's doing, however what I am struggling to understand is the formula used to cacluate the 10/90%, specifically "Int(Double(goal)". Can someone explain what is actually happening here?
I thought "step" was already an Int, so why would we need to set it to an Int and then to double? Or is this saying convert step which is an Init into a Double? (I think I may have just answered this while typing) but some clarification would be great, if anyone has time.
Thanks
One thing you should know is that Swift is stricter about numeric type treatment than many other languages.
- You cannot multiply Double and Int in Swift.
- You cannot compare Doulbe and Int in Swift.
You know that `goal` and `steps` are Int. And the default type of floating point literals like `0.1` and `0.9` are Double.
So, you cannot multiply `goal`, which is Int, and `0.1` (or `0.9`), which is Double. You need to convert `goal` to Double, and then you can multiply the convesion result to Double.
And, you cannot compare `steps`, which is Int, and the result of `Double(goal)*0.1`, which is Double. You need to convert `steps` to Double and then compare to `Double(goal)*0.1`. Or else, you need to convert `Double(goal)*0.1` to Int and then compare to `steps`, as shown in your code.
In your code, there are no parts converting `steps` into other types. `Double(goal)` converts `goal` to Double, `Int(Double(goal)*0.1)` converts `Double(goal)*0.1` to Int.