swift3中有一个长字符串,希望检查它是否包含word1、和 word2。它也可能是两个以上的搜索词。我发现了以下解决方案:
var Text = "Hello Swift-world"
var TextArray = ["Hello", "world"]
var count = 0
for n in 0..<TextArray.count {
    if (Text.contains(TextArray[n])) {
        count += 1
    }
}
if (count == TextArray.count) {
    print ("success")
}但这似乎很复杂,难道没有更容易的办法来解决这个问题吗?(Xcode8和swift3)
发布于 2017-01-27 20:45:01
一个更快速的解决方案将停止搜索它发现了一个不存在的词:
var text = "Hello Swift-world"
var textArray = ["Hello", "world"]
let match = textArray.reduce(true) { !$0 ? false : (text.range(of: $1) != nil ) }另一种在发现不匹配后停止的方法:
let match = textArray.first(where: { !text.contains($0) }) == nilhttps://stackoverflow.com/questions/41902580
复制相似问题