Reputation: 67
Is it possible to find the index of a NSMutableArray based on the begging of a string. For instance if I had the NSMutableArray ["Joe","Jim","Jason"]
and I wanted to find the index where the beginning of the string contains "Jo"
so that it would return index 0
for "Joe"
. Basically just trying to find an index based on part of a string rather than the whole string itself.
Upvotes: 0
Views: 205
Reputation: 63399
NSMutableArray
conforms to Collection
, and as such, it inherits the default method index(where:)
, which does exactly what you're looking for:
import Foundation
let names = ["Joe","Jim","Jason"]
let desiredPrefix = "Jo"
if let index = names.index(where: { $0.hasPrefix(desiredPrefix) }) {
print("The first name starting with \(desiredPrefix) was found at \(index)")
}
else {
print("No names were found that start with \(desiredPrefix)")
}
If you do this often, you can clean up your code by putting it in a function that extends Collection
s of String
s:
import Foundation
extension Collection where Iterator.Element == String {
func first(withPrefix prefix: String) -> Self.Index? {
return self.index(where: { $0.hasPrefix(prefix)})
}
}
let names = ["Joe","Jim","Jason"]
let desiredPrefix = "Jo"
if let index = names.first(withPrefix: desiredPrefix) {
print("The first name starting with \(desiredPrefix) was found at \(index)")
}
else {
print("No names were found that start with \(desiredPrefix)")
}
Upvotes: 1