尝试将文本附加到 Swift 循环中的属性



我有一个结构对象数组。 这些对象具有 title 属性(字符串(和位置属性(位置类型(。

我想从位置属性和距离函数与另一个现有位置对象派生的距离的双精度值附加到标题属性。 这是我正在使用的代码:

self.myList.map({$0.title.append("($0.location.distance(from: location!)/1000)")})

这里的问题是 map 函数返回一个新数组,但是,我需要对现有数组进行更改,因为我将此数组用作我的 UITableView 的数据源。 另一个问题是,尽管我将标题属性设置为变量,但总是告诉我以下错误消息:

Cannot use mutating member on immutable value: '$0' is immutable.

我该怎么做?

你应该像这样迭代数组:

for (i, _) in myList.enumerated() {
myList[i].title.append("(myList[i].location.distance(from: location) / 1000)")
}

你必须使用一个临时的可变变量:

myList = myList.map { (myStruct: MyStruct) -> MyStruct in
var mutableStruct = myStruct
mutableStruct.title.append("(element.location.distance(from: location) / 1000)")
return mutableStruct
}

最新更新