我想证明我的数组
let actualSigns = ["Aa", "Bb", "Cc"]
...等于这一个中的一个数组...
var validSigns = [[String]]()
validSigns.append(["Aa", "Bb", "Cc", "Dd"]) // want to match this
validSigns.append(["Aa", "Bb", "Cc", "Xy"]) // ... and this
validSigns.append(["Ee", "Ff", "Gg", "Hh"])
...仅比较actualSigns
的对象数量。
所以在这种情况下,我希望匹配validSigns
中的第一个和第二个数组,因为前三个值等于actualSigns
。
我尝试过滤它
let range = Range(start: actualSigns.count, end: actualSigns.count+1)
let match = validSigns.filter{ $0.removeRange(range) == actualSigns }
但是编译器说'$0 is a let constant'
。我该如何解决这个问题?
答案 0 :(得分:2)
我不确定我是否理解正确但您不需要使用范围来获得匹配:
// My original answer
let match = validSigns.filter { !zip($0, actualSigns).contains { $0.0 != $0.1 } }
// Based on Price Ringo's answer
let match = validSigns.filter { $0.startsWith(actualSigns) }
输出:
[["Aa", "Bb", "Cc", "Dd"], ["Aa", "Bb", "Cc", "Xy"]]
答案 1 :(得分:2)
答案 2 :(得分:0)
您可以通过执行以下操作来修复错误:
let match = validSigns.filter{ var input = $0; input.removeRange(range); return input == actualSigns }
其他一些方法,只是为了完整性:
import Foundation
let actualSigns = ["Aa", "Bb", "Cc"]
var validSigns = [
["Aa", "Bb", "Cc", "Dd"],
["Aa", "Bb", "Cc", "Xy"],
["Ee", "Ff", "Gg", "Hh"],
["Ee", "Aa", "Bb", "Cc"]] // Added another case, to test when the matching array is not at the start
let matches = validSigns.filter { $0.joinWithSeparator("").containsString(actualSigns.joinWithSeparator("")) }
// => [["Aa", "Bb", "Cc", "Dd"], ["Aa", "Bb", "Cc", "Xy"], ["Ee", "Aa", "Bb", "Cc"]]
let matches2 = validSigns.filter { Set($0).intersect(Set(actualSigns)).count == actualSigns.count }
// => [["Aa", "Bb", "Cc", "Dd"], ["Aa", "Bb", "Cc", "Xy"], ["Ee", "Aa", "Bb", "Cc"]]