【问题标题】:Checking if an index exists in a non-optional Array检查索引是否存在于非可选数组中
【发布时间】:2017-06-05 13:11:35
【问题描述】:

我有这个数组:

var currentTouches = [UITouch]()

在任何时候,它都可能包含 0-5 个UITouches。我想检查每个索引并对内容进行处理(如果存在)。

但我找不到不出错的检查方法。问题似乎是,UITouch 不是可选的,所以我不能只问是否是 @ 987654324@.

我该怎么办?我尝试将其设为可选,但这使得我的许多其他代码不寻常。肯定有一个简单的解决方案。

【问题讨论】:

  • for (index, touch) in currentTouches.enumerated() { // handle touch at index }
  • 您可以检查特定触摸项目的 index 是否为 nil 而不是项目本身。
  • 如果currentTouchesUITouch 的数组,要检查给定索引处是否存在对象,只需检查currentTouches.count > index
  • 你说的是estimationUpdateIndex吗?

标签: arrays swift xcode optional


【解决方案1】:

currentTouches 的有效索引就是currentTouches.indices。因此,要检查索引i 是否有效,您可以检查if currentTouches.indices.contains(i)。您也可以查看if i < currentTouches.count(假设您已经知道i >= 0)。

一种更简单的方法是循环有效索引并依次处理每个索引:

for index in currentTouches.indices {
    // handle value at index
}

或者如果您不关心索引:

for touch in currentTouches {
    // handle touch
}

更好的是使用enumerated(),它会为您提供一个包含索引和值的元组:

for (index, touch) in currentTouches.enumerated() {
    // handle touch at index
}

【讨论】:

    猜你喜欢
    • 2010-09-20
    • 2014-01-02
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2018-07-01
    • 2012-10-17
    • 2011-01-21
    相关资源
    最近更新 更多