swift - 循环工作,尝试 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
功能。
谢谢你的帮助。
解决方案
使它不那么模棱两可:
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
修改参数。
在此处了解有关函数参数不变性的更多信息:
函数参数默认为常量。尝试从该函数的主体内更改函数参数的值会导致编译时错误。
推荐阅读
- java - 如何在 GET 请求中排除其他类对象?- Java 春季启动
- python - 使用 Pyinstaller 转换为 Windows 的独立 Python 应用程序可以工作,但需要 23 秒才能启动
- spotfire - 如何使用属性控制作为 bin pruner
- java - Java:在定制的通用向量中间插入元素
- php-extension - 无法在 xampp php 7.3.2 中启用 php_intl.dll
- mysql - 为什么 GROUP_CONCAT 让我的查询更快?
- reactjs - Highcharts 对官方库的反应不能很好地与 Typescript 配合使用
- java - 此 Java 代码中的漏洞是什么?
- python - 连续执行多个python脚本
- python - 为什么我不能在 Django 中打印选择模型实例?