2017-08-18 30 views
0

我有一個結構對象數組。這些對象有一個屬性(它是一個字符串)和一個屬性(位置類型)。試圖將文本追加到Swift循環中的屬性中

我想追加一個雙重值的距離派生自位置屬性和距離函數與另一個現有的位置對象到標題屬性。這裏是我一起工作的代碼:

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

這裏的問題是,map函數會返回一個新的數組,但是,我需要做出改變現有的陣列,因爲我使用這個數組我的UITableView的數據源。另一個問題是,儘管我做標題屬性變種,我總是跟以下錯誤消息:

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

任何人都可以找出如何做到這一點?

+0

重新分配的結果返回給'self.myList' – Alexander

+0

@Alexander我該怎麼做? – syedfa

+1

'self.myList = self.myList.map({$ 0.title.append($ 0.location.distance(from:myLocation!)/ 1000)})' – Alexander

回答

1

你應該遍歷數組這樣過:

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

@Alexander更新了我的答案... –

+0

由於一些奇怪的原因,你的原始答案工作,但這一個沒有。出於某種原因,文本不會被附加到標題屬性中。任何想法爲什麼? – syedfa

0

你不得不使用臨時可變變量:

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