我是一名 Javascript 开发者,我喜欢使用 not/negate
函数:
function not (predicateFunc) {
return function () {
return !predicateFunc.apply(this, arguments);
};
}
我正在尝试用 swift 做同样的事情:
func not <A> (_ f: @escaping (_ A: Any) -> Bool) -> (A) -> Bool {
return { a in !f(a) }
}
但是我遇到了这样的错误
generic parameter 'T' could not be inferred
和
Cannot convert value of type '(_) -> Bool' to expected argument type '(Any) -> Bool'
我正在寻找的结果是当我有这样的功能时:
func isEmpty<T: Collection>(collection: T) -> Bool {
return collection.count == 0
}
我可以像这样创建一个 notEmpty
函数:
let notEmpty = not(isEmpty)
然后像这样使用它
notEmpty([3,4,5]) // true
我做错了什么?
最佳答案
使用 Any
是一种代码味道。您可以直接扩展 Collection:
extension Collection {
var notEmpty: Bool {
return !isEmpty
}
}
[1, 3, 5].notEmpty // true
not
的函数定义可以像这样工作:
func not <A> (_ f: @escaping (_ a: A) -> Bool) -> (A) -> Bool {
return { a in !f(a) }
}
但是要调用它你需要这样的东西:
let arrayNotEmpty = not { (array: [Int]) in array.isEmpty }
arrayNotEmpty([1, 3, 5]) // true
关于swift - 如何在 swift 中编写 not/negate 高阶函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53975326/