【问题标题】:iOS - Swift - Loop for with array and conditioniOS - Swift - 使用数组和条件循环
【发布时间】:2016-01-28 10:30:00
【问题描述】:

我正在寻找对数组执行循环但想在某个条件后停止。这就是我现在所拥有的(顺便说一句,我使用 Parse 作为后端)。

let query = PFQuery(className: "MyObject")
query.whereKey("user", equalTo: PFUser.currentUser())
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
        if error == nil {
            for object in objects {
                print(object.objectId)
            }
        }
}

此代码正在打印每个 objectId。

现在让我们假设我想打印每个对象直到我找到一个带有objectId == "xxx" 的对象。

我该怎么做?

【问题讨论】:

  • 您可以返回或跳出循环。如果 objectId == "xxx" { 中断/返回 }
  • Swift没有break的概念吗?这是大多数语言中从循环中转义的标准方法。

标签: ios arrays swift for-loop conditional


【解决方案1】:

试试这个

 for object in objects {
            print(object.objectId)

      if object.objectId == "xxx"
       {
         // object Name is found
         // if you like to break the execution use "break"
         //break
        }
       else
        {
          // object ID not found
        }
      }

【讨论】:

    【解决方案2】:

    我认为filter 就是您要找的东西

    let objects = [["id": 1], ["id": 2], ["id": 3]]
    objects.filter { $0["id"] != 3 }.forEach { print($0) }
    

    【讨论】:

      【解决方案3】:

      如果要过滤objId并执行一些代码:

      let array = ["id1", "id2", "id3", "id4"]
      for objId in array where objId != "id3" {
          print(objId)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-16
        • 1970-01-01
        • 2015-03-02
        • 2021-03-20
        • 1970-01-01
        • 2021-11-23
        • 2021-03-25
        相关资源
        最近更新 更多