【问题标题】:How can I make a loop in swich case(swift)?如何在 switch case(swift) 中创建一个循环?
【发布时间】:2015-07-10 14:07:35
【问题描述】:

我编写了该代码,但无法在错误条件下创建循环。如何为错误条件创建循环?

注意:“isConnectedToNetwork()”返回一个布尔表达式。

switch Reachability.isConnectedToNetwork() {
    case false :
        println("Internet connection FAILED")
        var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
        alert.show()
        fallthrough
     default:
         println(“Internet connection OK")
}  

【问题讨论】:

  • 如果它是一个布尔值,你为什么不直接使用if(Reachability.isConnectedToNetwork(){print internet ok}else{show alert}
  • 我会重新阅读您在 switch 语句中阅读的所有内容。在处理布尔值的开关上添加失败有点奇怪。为假的那一刻,也会执行默认的。您的代码中也没有任何循环。 Switch 语句与循环的距离差不多,因为它们执行第一个匹配的 case 一次。如果您需要循环,请使用 while 或 do while
  • 如果你想在它改变时得到通知,你需要实现可达性回调:developer.apple.com/library/ios/samplecode/Reachability/…

标签: ios xcode swift loops boolean


【解决方案1】:
while !Reachability.isConnectedToNetwork() {
   println("Internet connection FAILED")
   var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
   alert.show()
}
println("Internet connection OK")

虽然这回答了您的问题,但这是一个非常糟糕的想法。请不要在任何应用程序中实际使用它,而是需要按照@i_am_jorf 的建议实现reachability callbacks,或者重新考虑此代码的设计

【讨论】:

    猜你喜欢
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多