简体   繁体   中英

Finding Strings in a NSMutableArray Swift

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.

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)")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM