在Swift中检查字符串是否包含字典中的某个子字符串



我想检查一个字符串是否包含字典中的一个字符串。字典将EKCalendar对象映射到字符串数组。下面的代码适用于另一种方法(检查字典是否包含字符串)

// 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
}

为了解决您的问题,我编写了一个函数来检测项目是否是字符串的一部分:

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地图你的字典:

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

最新更新