ios - Swift 函数式编程 - 有没有比两个 map 调用更好的方法来翻译嵌套的 for 循环

标签 ios swift functional-programming higher-order-functions

我已经将嵌套的 for 循环转换为嵌套的 map 调用。我想知道是否有更优雅的实现方式。

这里是一个函数,它接受 ItemArray 和函数的 Array (Item -> Item) 并返回一个数组,其中包含应用于每个项目的所有函数:

typealias Item = Dictionary<String, String>    

func updatedItems(items: Array<Item>, fns: Array<Item -> Item>) -> Array<Item> {
    return items.map {
        item in

        var itemCopy = item
        fns.map { fn in itemCopy = fn(itemCopy) }

        return itemCopy
    }
}

最佳答案

内部 map() 调用不会返回一个新数组,它只是为了产生副作用。这行得通,但有时“不受欢迎”(见 例如 Higher order function: "Cannot invoke 'map' with an argument list of type '((_) -> _)'" ).

将所有功能依次应用于单个项目的“正确”方法是 使用reduce:

func updatedItems(items: Array<Item>, fns: Array<Item -> Item>) -> Array<Item> {
    return items.map {
        item in
        fns.reduce(item) {
            (curItem, fn) in
            fn(curItem)
        }
    }
}

或使用速记参数名称:

func updatedItems(items: Array<Item>, fns: Array<Item -> Item>) -> Array<Item> {
    return items.map {
        fns.reduce($0) { $1($0) }
    }
}

另请注意,您可以将数组符号缩短为

func updatedItems(items: [Item], fns: [Item -> Item]) -> [Item] { ... }

关于ios - Swift 函数式编程 - 有没有比两个 map 调用更好的方法来翻译嵌套的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31777004/

相关文章:

visual-studio - F# VS2019 Windows 窗体

ios - 创建要在选择器 View 中使用的数字数组不起作用

ios - 无法更新自定义 UITableViewCell 中 UITextView 的文本

swift - 在暂停后的 AVAudioPlayer 中,歌曲不会在 Swift 上继续播放

c# - 字符串列表到一个字符串

C++:使用 mem_fn 和 bind1st 创建函数对象

ios - 由于 API key 无效(格式错误或丢失),操作失败

ios - 安装 cocoa pod 时传递依赖性错误

swift - 并发队列中的 DispatchQueue 同步与同步屏障

ios - 章节标题困惑