簡體   English   中英

在 UserDefaults 中的數組中更改字典中的值

[英]Changing value in Dictionary in a Array in UserDefaults

我在更改數組中字典的值時遇到問題

var array = (defaults.array(forKey: "Transactions")! as! [Dictionary<String, Any>])
        
(array.reversed()[index]["Title"] as! String) = titleTextField.text! // Cannot assign to immutable expression of type 'String'

無法分配給“字符串”類型的不可變表達式

這是我回來的錯誤

這個問題有解決方案嗎?

正如 Joakim 指出的,array.reversed() 返回一個不可變的數組。

嘗試這個:

guard 
  var array = (defaults.array(forKey: "Transactions")! as? [Dictionary<String, Any>]),
  let newText = titletextfield.text,
array[array.count-index]["Title"] = newText

(然后將您的數組重新保存到 UserDefaults)

再多走一步

if var array = UserDefaults.standard.array(forKey: "Transactions") as? [Dictionary<String, Any>], let valueText = titleTextField.text {
    array.reverse()
    array[index]["Title"] = valueText
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM