【问题标题】:Trying to append text to a property inside a loop in Swift尝试将文本附加到 Swift 循环内的属性
【发布时间】:2017-08-18 19:20:52
【问题描述】:

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

我想要的是将从 location 属性和具有另一个现有 Location 对象的 distance 函数派生的距离的 double 值附加到 title 属性。这是我正在使用的代码:

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

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

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

谁能弄清楚如何做到这一点?

【问题讨论】:

  • 将结果重新分配给self.myList
  • @Alexander 我该怎么做?
  • self.myList = self.myList.map({$0.title.append($0.location.distance(from: myLocation!)/1000)})
  • 等等,你为什么在map中调用appendappend 什么也不返回 (Void)
  • 我正在尝试将一个字符串添加到现有的字符串属性中。

标签: ios swift struct


【解决方案1】:

你应该像这样遍历数组:

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

【讨论】:

  • 出于某种奇怪的原因,您的原始答案有效,但这个无效。由于某种原因,文本未附加到 title 属性。知道为什么吗?
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    相关资源
    最近更新 更多