检查Swift中字符串是否包含字典

时间:2016-04-11 13:27:15

标签: swift dictionary functional-programming

我想检查一个字符串是否包含字典中的一个字符串。字典将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
}

1 个答案:

答案 0 :(得分:1)

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

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

比我映射你的字典:

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