Joseph Toronto Joseph Toronto -5 years ago 94
Swift Question

Find match in array for given string?

Ok so lets say I have an custom object for vocabulary words, alternate way of being written, and their meaning.

class VocabEntry {
var kanji:String?
var kana:String?
var meaning:String?

Then I have an array comprised of these objects. Here's one for example.

let newVocabWord = VocabEntry()
newVocabWord.kanji = "下さい”
newVocabWord.kana = "ください”
newVocabWord.meaning = "please"

Now I have a string of text:

let testString = "すみません、十階のボタンを押して下さい"

How can I compare that string to my array of custom objects (that contain strings) and reference the matches?

I tried.

if vocabArray.contains( { $0.kanji == testString }) {

But that trying to match the entire string. If I change
to "下さい" it works, but that's not what I'm looking for. What I want is for it to say "Here I found 下さい in xx object. Here's the index number."

Answer Source

You can use indexOf() with a predicate to find the index of a matching entry, and containsString() to search for substrings. Since the kanji property is optional, you have to check that via optional binding:

if let index = vocabArray.indexOf({ entry in
    if let kanji = entry.kanji {
        // check if `testString` contains `kanji`:
        return testString.containsString(kanji)
    } else {
        // `entry.kanji` is `nil`: no match
        return false
}) {
    print("Found at index:", index)
} else {
    print("Not found")

This can be written more concise (but not necessarily more readable) as

if let index = vocabArray.indexOf({
    $0.kanji.flatMap { testString.containsString($0) } ?? false
}) {
    print("Found at index:", index)
} else {
    print("Not found")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download