问题描述
我有一个FUNCTION,可以从函数数组中返回一个随机函数。
我希望返回的函数在再次调用FUNCTION时不会连续两次随机返回,所以我使用一个空数组来存储最后返回的函数,然后每次使用FUNCTION时都对原始数组使用过滤器被调用以排除返回的最后一个函数。
由于某种原因,FUNCTION返回数组中的所有函数,而不是随机返回一个函数。
当我检查过滤后的数组是否包含函数时,它也会打印0。所以我很困惑。
stacked widgets
解决方法
您正在使用lastFunction
类型的Array<()>()
,然后将其与下面的代码中的单个函数()
元素进行比较,
let filteredArray: [()] = arrayOfFunctions.filter( { return ($0 != lastFunction)})
相反,您必须使用()?
作为lastFunction
类型,然后进行相关比较,即
func myFunction() -> () {
var arr = Array<()>()
if let value = lastFunction {
arr = arr.filter { $0 != value }
} else {
arrayOfFunctions.append(function1())
arrayOfFunctions.append(function2())
arr = arrayOfFunctions
}
guard let nextFunction = arr.randomElement() else { return arr[0] }
lastFunction = nextFunction
return nextFunction
}