我想将Set<Int>
作为参数传递给函数。当我这样做时:
let setsOfWinningCells: Set = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ]
func isWinner(playerCells: Set<Int>) {
for winningCells in setsOfWinningCells {
if playerCells.isSupersetOf(winningCells) {
// do something
}
}
}
编译器抱怨它cannot invoke 'isSuperSetOf' with an argument list of type '(NSArray)'
。使用Set<Int>()
代替Set<Int>
也不起作用。
有谁知道正确的语法?感谢
澄清:
我错误地认为问题是将Set正确地传递给函数,但事实上问题并没有正确定义Set of Set。为混淆道歉。
答案 0 :(得分:0)
winnerCells是NSArray,你应该为isSupersetOf(_)函数传递一个Set
答案 1 :(得分:0)
让我们尝试更好地定义您的问题。
让我们定义一个结构来表示一组Hashable
的概念。我们还希望结构为struct Group: Hashable {
let values: Set<Int>
var hashValue: Int { return values.hashValue }
}
func ==(left:Group, right:Group) -> Bool {
return left.values == right.values
}
。
let winningGroups: Set<Group> = [
Group(values:[0,1,2]),
Group(values:[3,4,5]),
Group(values:[6,7,8]),
Group(values:[0,3,6]),
Group(values:[1,4,7]),
Group(values:[2,5,8]),
Group(values:[0,4,8]),
Group(values:[2,4,6])
]
现在让我们创建一个获胜组列表
let playerGroups: Set<Group> = [
Group(values:[4,0,8]),
Group(values:[2,4,6])
]
接下来我们有一个玩家组列表
playerGroups
现在,我们要选择winningGroups
和let playerWinningGroups = playerGroups.intersect(winningGroups)
//[Group(values: Set([5, 4, 3])), Group(values: Set([2, 0, 1]))]
中的所有群组。
Int(s)
正如您所见,本集团内
[4,3,5]
的订单不相关。E.g。玩家有
[3,4,5]
,获胜组为let playerGroups: Set<Group> = [ Group(values:[4,0,8]), Group(values:[2,4,6]), Group(values:[6,7,8,9]), ]
。即使值的顺序不同,该组仍会添加到结果中。
让我们考虑一下这个玩家群体
[6,7,8,9]
第三组是获胜组var res = Set<Group>()
playerGroups.forEach { (playerGroup) in
if (winningGroups.contains({ (winninGroup) -> Bool in return winninGroup.values.isSubsetOf(playerGroup.values) })) {
res.insert(playerGroup)
}
}
print(res) // [Group(values: Set([2, 4, 6])), Group(values: Set([6, 7, 9, 8])), Group(values: Set([4, 0, 8]))]
的超集。但是,之前的解决方案并未选择此元素。
让我们看一个能够返回winsGroups超群组的解决方案
sudo gem install bond
答案 2 :(得分:0)
谢谢你,哈米什,指出我错过了什么。我的问题是没有错误地传递Set,而是我的Set
Set<Int>
未正确定义。我原来的定义意味着它是Set
Arrays
Int
。应该是:
let setsOfWinningCells: Set<Set<Int>> = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ]