Home > Back-end >  Assistance with if statements in swift
Assistance with if statements in swift

Time:11-14

I'm new to programming and was trying to figure out how I get else if statements to read my variable and range operator in Swift? I cant use a switch and need to use if statements.

var Fahrenheit = 10
if Fahrenheit <0 {
    print("Too Cold for Outdoors")
    }
else if Fahrenheit == 0 - 20 {
    print("Very Cold Weather");
    }
else if Fahrenheit == 21 - 40{
    print("Cold")
    }
else if Fahrenheit == 41 - 60{
    print("Normal");
    }
else if Fahrenheit == 60 - 80{
    print("Nice");
    }
else if Fahrenheit == 81 - 90{
    print("Warm");
    }
else if Fahrenheit >90 {
    print("Hot");
    }

CodePudding user response:

The ... operator creates a ClosedRange, and ClosedRange has a contains method.

var fahrenheit = 10

if fahrenheit < 0 {
    print("Too Cold for Outdoors")
} else if (0 ... 20).contains(fahrenheit) {
    print("Very Cold Weather");
} else if (21 ... 40).contains(fahrenheit) {
    print("Cold")
} else etc. etc. etc

If you don't want to use ..., you can write explicit comparisons. Note that because we're checking the ranges in ascending order, we only need to test the upper bound of each range to get the correct answer:

var fahrenheit = 10

if fahrenheit < 0 {
    print("Too Cold for Outdoors")
} else if fahrenheit <= 20 {
    print("Very Cold Weather");
} else if fahrenheit <= 40  {
    print("Cold")
} else etc. etc. etc.

But if you really want to test both bounds of each range, you can do so like this:

var fahrenheit = 10

if fahrenheit < 0 {
    print("Too Cold for Outdoors")
} else if 0 <= fahrenheit && fahrenheit <= 20 {
    print("Very Cold Weather");
} else if 20 < fahrenheit && fahrenheit <= 40  {
    print("Cold")
} else etc. etc. etc.
  • Related