循环工作,尝试 map-reduce 时出错

Loop works, get error when trying 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: ", {[=11=].append(.toString())}))

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

var geometryToAdd: Array<Geometry> = []

并且 class Geometry 具有 toString 函数。

感谢您的帮助。

让它不那么模棱两可:

print(geometryToAdd.reduce("Geometry add to map: ", {
      [=10=] + .toString()
}))

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

看看reduce

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

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

了解有关函数参数不变性的更多信息here

Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error.

类似的方法有两种:

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

您使用的是第一个版本,其中 [=12=] 是不可变的,闭包 必须 return 累加值。这不会编译,因为 append() 修改其接收器。

使用第二个版本使其编译:这里 [=12=] 是可变的并且 闭包使用累加值更新 [=12=]

print(geometryToAdd.reduce(into: "Geometry add to map: ", {[=11=].append(.toString())}))

你最好使用 joined(separator:) 而不是 reduce。它具有更好的性能,如果您愿意,可以让您放入分隔符:

print("Geometry add to map: \(geometryToAdd.map(String.init).joined(separator: "")")