Larry Larry - 3 years ago 80
Swift Question

Why won't swift allow nested if statements along with others?

So for the past hour or so, I've been trying to nest three if statements in swift but nothing is working. I'm literally pulling my hair out for something that seems so simple and yet I have no idea what I am doing wrong. Any help is appreciated.

var population = 125442
var message: String
var hasAPostOffice: Bool = true

if population < 10000 {
message = "\(population) is a pretty small town"
}else if population >= 10000 && population < 50000 {
message = "\(population) is a medium sized town"
}else{
message = "\(population) is a very large town!"
}else = {
population >= 200000 && population < 120000 {
message = "\(population) is a super huge town"
}
}
print(message)

if !hasAPostOffice {
print("Where could I buy stamps?")
}

Answer Source

Just replace your condition with the below code.

var population = 125442
var message: String
var hasAPostOffice: Bool = true

if population < 10000 {
    message = "\(population) is a pretty small town"
}else if population >= 10000 && population < 50000 {
    message = "\(population) is a medium sized town"
}else if population >= 200000 && population < 120000 {
    message = "\(population) is a super huge town"
}else{
    message = "\(population) is a very large town!"
}

print(message)

if !hasAPostOffice {
    print("Where could I buy stamps?")
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download