Daniel
Daniel

Reputation: 3868

Check in Swift whether string contains one of the substrings in a dictionary

I'd like to check whether a string contains one of the strings in a dictionary. The dictionary maps EKCalendar objects to arrays of strings. The below code works for the other way around (checking whether the dictionary contains the string.)

// cal1, cal2, cal3 are of type EKCalendar
let dict = [cal1 : ["this is", "another test case"], cal2 : ["red color", "green color"], cal3 : ["Hello World", "how are", "you"]]

let stringToCheckContent = "this is one of my sample sentences"
let keys = dict.filter {
//    return $0.1.contains(stringToCheckContent)      // This of course works for the inverse case - if i check whether dictionary has as a part the stringToCheckContent.
    return stringToCheckContent.contains($0.1)      // should return cal1. However I get "Value of type 'String' has no member 'contains'.
    }.map {
        return $0.0
}

Upvotes: 0

Views: 921

Answers (1)

Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

For solving of youre issue i write function that detect if item is a part of string:

func ifItemExistInString(vals: Array<String>) -> Bool {
    var state = false
    vals.forEach { (key: String) -> () in
        if (stringToCheckContent.lowercaseString.rangeOfString(key) != nil) {
            state = true
        }
    }
    return state
}

Than i map you're dictionary:

let keys = dict.filter {
    return ifItemExistInString($0.1)
    }.map {
        return $0.0
}

Upvotes: 1

Related Questions