首页 > 解决方案 > 循环工作,尝试 map-reduce 时出错

问题描述

我是 map-reduce 的新手,想尝试一下。我希望这个问题不会太愚蠢。

我有这个代码工作:

var str = "Geometry add to map: "
for element in geometryToAdd {
     str.append(element.toString())
}
print(str)

现在我想玩一下 map-reduce,因为我最近学会了它。我把它改写成这样:

print(geometryToAdd.reduce("Geometry add to map: ", {$0.append($1.toString())}))

这给了我一个错误error: MyPlayground.playground:127:57: error: type of expression is ambiguous without more context。我做错了什么?

var geometryToAdd: Array<Geometry> = []

并且该类Geometry具有toString功能。

谢谢你的帮助。

标签: swiftmapreduce

解决方案


使它不那么模棱两可:

print(geometryToAdd.reduce("Geometry add to map: ", {
      $0 + $1.toString()
}))

错误来自这样一个事实,即您只能append()对可变序列:$0是不可变的String。在循环中,str是可变的: a var,而不是 a let

看一下签名reduce

func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

nextPartialResult是一个函数/闭包,它接受两个参数并给出一个结果。此函数的参数是不可变的,它们不是inout参数。只能inout修改参数。

在此处了解有关函数参数不变性的更多信息:

函数参数默认为常量。尝试从该函数的主体内更改函数参数的值会导致编译时错误。


推荐阅读