Reputation: 520
I have this code below that's looping through all the key string in Dictionary
. All is well until I want to search string that is not on the Dictionary. When I search string that's not in the Dictionary
, my code should have been doing one more loop then fall in to else of if index != patternFromDatabase.count
, but it won't since the for loop is finished by the enumerated count of the patternFromDatabase
.
How can I do for-loop one last time after enumerated is finished since I cant just write patternFromDatabase.enumerated() + 1
.
Do you have any suggestion? or Should I modify my code a little bit so I don't have to face this problem to outcome my purpose? Thank you very much. If you need more explanation I'll be happy to explain the code for you.
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)")
}
}
Upvotes: 1
Views: 73
Reputation: 539745
Should I modify my code a little bit so I don't have to face this problem to outcome my purpose?
Yes. There are standard library methods to check if an array contains an element with given properties. In your case:
if patternFromDatabase.contains(where: { key in Algorithm().searchStringWithBitap(key, pattern: insertedPattern) != -1 }) {
print("found:", key)
} else {
print("not found")
}
Or, if the index of the found element is relevant:
if let idx = patternFromDatabase.index(where: { key in Algorithm().searchStringWithBitap(key, pattern: insertedPattern) != -1 }) {
print("found at:", idx)
} else {
print("not found")
}
References:
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.
Upvotes: 1
Reputation: 6067
Swift 3.0
// asssyme haveResult is Bool for result
// if you need one more loop even if he get result you can use same way
let dict = ["c": 123, "d": 045, "a": 456]
for (index, entry) in dict.enumerated() {
if index == dict.count-1 { // Last loop
if !haveResult {
// make external call
}
}
}
Upvotes: 0