Reputation:
I'm fairly new to Swift and this has got me stumped. I have :
for values in input {
if num >= 80 {
message = "hot!"
}
else if num >= 60 && num < 80 {
message = "warm!"
}
else if num >= 40 && num < 60 {
message = "cool!"
}
else if num <= 40 {
message = "cold!"
}
print("The temperature \(values) is \(message)")
}
And this is printing as
"Please enter a temperature 65"
"Please enter a temperature 1"
"Please enter a temperature 100"
"Please enter a temperature 56"
"Please enter a temperature 46"
"The temperature 65 is warm!"
"The temperature 1 is warm!"
"The temperature 100 is warm!"
"The temperature 56 is warm!"
"The temperature 46 is warm!"
As you can see it's not going one by one but instead naming each element of array the same. What am I doing wrong here? I'm using readLine() for the array elements.
Upvotes: 0
Views: 586
Reputation: 7485
You can use like this:
for value in input {
if value >= 80 {
message = "hot!"
}
else if value >= 60 && value < 80 {
message = "warm!"
}
else if value >= 40 && value < 60 {
message = "cool!"
}
else if value <= 40 {
message = "cold!"
}
print("The temperature \(value) is \(message)")
}
Upvotes: 0
Reputation: 93161
Since you are learning Swift, you need to learn a couple conventions:
inputs
instead of input
.value
instead of values
.value
instead of num
Other than that, you can write your code more concisely using switch
:
for value in inputs {
var message = ""
switch value {
case 80...: // equivalent to: if 80 <= num
message = "hot!"
case 60..<80: // equivalent to: if 60 <= num && num < 80
message = "warm!"
case 40..<60: // equivalent to: if 40 <= num && num < 60
message = "cool"
case ..<40: // equivalent to: if num < 40
message = "cold"
default:
message = "" // this is actually not reachable since the cases above cover
// all possible scenarios. But Swift require switch statement
// to be exhaustive and it doesn't go that deep to prove that
// we already had everything covered. This is to silence the
// compiler.
}
print("The temperature \(value) is \(message)")
}
Upvotes: 1
Reputation: 2632
In your for loop you are comparing num against your temp range and not the values variable. So i believe that the value of num has been defined outside of the array itself and never mutated.
With that being said I believe a switch statement would better suit ur needs and would be much cleaner in this case.
Just don’t forget to compare the values and not the num variable
Upvotes: 0