gpt4 book ai didi

ios - 快速使用高阶函数

转载 作者:行者123 更新时间:2023-12-01 18:39:58 24 4
gpt4 key购买 nike

我正在学习来自Haskell背景的Swift,我想将这一点转换为Swift:

match :: Int -> Bool
match = (>) 3

hasMatch :: (Int -> Bool) -> [Int] -> [Int]
hasMatch pred ns = filter pred ns

hasMatch match [1..5] = [4,5]

我知道这个愚蠢的例子。这就是我的迅速:
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,这没有任何意义。所有功能都必须具有命名输入吗?
  • 我将如何更改代码以编译
  • 最佳答案

    func hasMatch(pred: (Int) -> Bool, ns: [Int]) -> [Int] {
    return ns.filter { n in pred(n) }
    }

    如果函数是闭包,则不需要参数名称。
    @escaping是swift中的一个关键字,它告诉编译器传入的函数将转义当前作用域,因此它需要保留/释放传入的参数(Swift与Objective-C一样,使用保留计数进行内存管理)

    但是,在这种情况下,您不需要它-该错误是编译器抛出的红色鲱鱼,因为它无法使用 filter编译行,因此它不知道是否需要转义。看起来很安全:)

    一旦删除了 n:,它就可以计算出要调用的 filter,它知道由于 filter不需要 @escaping闭包,因此您的方法也不需要,因此错误消失了。

    关于ios - 快速使用高阶函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44784228/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com