【发布时间】:2018-12-30 04:40:57
【问题描述】:
我是一名 Javascripter,我喜欢使用 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
我做错了什么?
【问题讨论】:
标签: swift functional-programming higher-order-functions