为什么赢得swift允许嵌套if语句和其他语句?

时间:2017-07-26 04:49:49

标签: swift if-statement nested

所以在过去的一个小时左右,我一直试图在swift中嵌套三个if语句,但没有任何工作。我真的把头发拉出去看似简单的东西,但我不知道我做错了什么。任何帮助表示赞赏。

-(void)buildUsersInDatabase {
    FIRDatabaseReference *referenceToDatabase = [[FIRDatabase database]reference];
    [[referenceToDatabase child:@"Users"]observeEventType: FIRDataEventTypeChildAdded withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
        if (!self.dict){
            self.dict = [NSMutableDictionary new];
        }
        [self.dict setObject:snapshot.value forKey:snapshot.key];

    }];
}

4 个答案:

答案 0 :(得分:2)

您的嵌套应该看起来像 -

export OS_USER_DOMAIN_ID=default
export OS_PROJECT_DOMAIN_ID=default
export OS_USERNAME=admin
export OS_PROJECT_NAME=admin
export OS_PASSWORD=passw0rd
export OS_IDENTITY_API_VERSION=3
export OS_AUTH_URL=http://devops.taobao.com:35357/v3
export OS_IMAGE_API_VERSION=3

这是什么条件

API version 3 parameter

在我看来,这绝不是真的,因为人口不能同时低于120000和超过200000。

所以检查你的逻辑

答案 1 :(得分:0)

您遇到的问题不仅限于Swift。每个else语句必须只与一个if语句相关联。

在您的代码中,您有两个else语句。如果因为尝试获得评估的尝试条件,那么其他一些语句看起来应该是其他语句。因此,如果您的条件取决于表达式,请在其中创建else if语句。

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!"
}

答案 2 :(得分:0)

看起来你的逻辑是关闭的;解决方案是将最终的else添加为最大值:

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 >= 50000 && population < 120000 {
    message = "\(population) is a very large town"
} else if population >= 120000 && population < 200000 {
    message = "\(population) is a super huge town"
} else {
    message = "\(population) is enormous!"
}

答案 3 :(得分:0)

这对switch语句更有效:

let population = 125442
let hasAPostOffice = true

let message: String
switch population {
    case 0 ..< 10_000: message = "\(population) is a pretty small town"
    case 10_000 ..< 50_000: message = "\(population) is a medium sized town"
    case 120_001 ... 200_000: message = "\(population) is a super huge town"
    default: message = "\(population) is a very large town!"
}

print(message)

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