下面的代码循环遍历 Dictionary
中的所有键字符串。一切都很好,直到我想搜索不在字典中的字符串。当我搜索不在 Dictionary
中的字符串时,我的代码本应再执行一个循环然后落入 if index != patternFromDatabase.count
的 else,但它赢了't 因为 for 循环由 patternFromDatabase
的枚举计数完成。
我怎么能在枚举完成后最后一次做 for 循环,因为我不能只写 patternFromDatabase.enumerated() + 1
。
你有什么建议吗?或者我应该稍微修改一下我的代码,这样我就不必面对这个问题来实现我的目的吗? 非常感谢。如果您需要更多解释,我很乐意为您解释代码。
for (index, key) in patternFromDatabase.enumerated() {
let startTimeForBitap = Date()
print("i: \(index), db: \(patternFromDatabase.count), key: \(key)")
if index != patternFromDatabase.count {
if Algorithm().searchStringWithBitap(key, pattern: insertedPattern) == -1 {
continue
} else {
let endTimeForBitap = Date().timeIntervalSince(startTimeForBitap)
bitapRunningTime.text = "\(convertTimetoMS(time: endTimeForBitap)) ms"
print("BITAP FOUND: \(endTimeForBitap)")
let bitapTextResult = pattern[key]
print(bitapTextResult ?? "")
bitapTextLabel.text = bitapTextResult
bitapPatternLabel.text = key
break
}
} else {
let endTimeForBitap = Date().timeIntervalSince(startTimeForBitap)
bitapTextLabel.text = "Pattern NOT FOUND"
bitapPatternLabel.text = "Pattern NOT FOUND"
bitapRunningTime.text = "\(convertTimetoMS(time: endTimeForBitap)) ms"
print("BITAP NOT FOUND: \(endTimeForBitap)")
}
}
最佳答案
Should I modify my code a little bit so I don't have to face this problem to outcome my purpose?
是的。有标准库方法可以检查数组是否包含 具有给定属性的元素。在你的情况下:
if patternFromDatabase.contains(where: { key in Algorithm().searchStringWithBitap(key, pattern: insertedPattern) != -1 }) {
print("found:", key)
} else {
print("not found")
}
或者,如果找到的元素的索引是相关的:
if let idx = patternFromDatabase.index(where: { key in Algorithm().searchStringWithBitap(key, pattern: insertedPattern) != -1 }) {
print("found at:", idx)
} else {
print("not found")
}
引用资料:
Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
Returns the first index in which an element of the collection satisfies the given predicate.
关于ios - 在 For Enumerated 中再循环一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45779857/