【发布时间】:2017-06-27 15:27:53
【问题描述】:
我正在学习 swift 来自 Haskell 背景,我想将这一点翻译成 swift:
match :: Int -> Bool
match = (>) 3
hasMatch :: (Int -> Bool) -> [Int] -> [Int]
hasMatch pred ns = filter pred ns
hasMatch match [1..5] = [4,5]
我知道的愚蠢的例子。这就是我使用 swift 所拥有的:
func hasMatch(pred : (Int) -> Bool, ns : [Int]) -> [Int]{
return ns.filter{n in pred(n:n)}
}
func match(n: Int) -> Bool{
return n > 3
}
let os = hasMatch(pred : match, ns: [1,2,3,4,5])
不编译。这是错误信息:
let os = hasMatch(pred : match, ns: [1,2,3,4,5])
./hello-swift.swift:48:28: error: extraneous argument label 'n:' in call
return ns.filter{n in pred(n:n)}
^~~
./hello-swift.swift:48:24: error: closure use of non-escaping parameter 'pred' may allow it to escape
return ns.filter{n in pred(n:n)}
^
./hello-swift.swift:47:15: note: parameter 'pred' is implicitly non-escaping
func hasMatch(pred : (Int) -> Bool, ns : [Int]) -> [Int]{
^
@escaping
我有两个问题:
我有
pred(n:n),但这假设pred将其输入命名为n,这没有意义。所有函数都必须有命名输入吗?如何更改代码以便编译
【问题讨论】:
-
闭包失去了它们的参数标签。只是
return ns.filter{n in pred(n)}