gpt4 book ai didi

ios - Swift - 将字典数组保存到 NSUserDefaults

转载 作者:IT王子 更新时间:2023-10-29 05:20:51 44 4
gpt4 key购买 nike

我有一个空的购物车数组 -> var cart: [Dictionary<String, Any>] = []

我有 2 个屏幕,productsView 和 resumeView。进入产品 View 我有一些产品。当用户点击产品时,这会转到购物车:

cart = [[name: "A", price: "1", qty: "1"]]

如果用户点击更多产品:

cart = [[name: "A", price: "1", qty: "3"],[name: "B", price: "2", qty: "1"]]

现在,当用户将产品添加到购物车后,我想显示带有产品列表的第二个 View ,用户可以更改产品“数量”或删除产品。如果用户点击返回并转到第一个屏幕,我想显示更新后的列表。

我想使用 NSUserDefaults 来保存我的数组并在屏幕之间显示更新的数据。但我收到下一个错误:

Type '[Dictionary<String, Any>]' does not conform to protocol 'AnyObject'

最佳答案

编辑/更新:在 Swift 3 中,您的字典类型就可以了。

Dictionaries

Swift also bridges between the Dictionary type and the NSDictionary class. When you bridge from an NSDictionary object with parameterized types to a Swift dictionary, the resulting dictionary is of type [Key: Value]. If an NSDictionary object does not specify parameterized types, it is bridged to a Swift dictionary of type [AnyHashable: Any]

因此,在 Swift 3 中将字典数组声明为 [[String: Any]] 会很好:


Xcode 8 • Swift 3

var cart: [[String: Any]] = []
cart.append(["name": "A", "price": 19.99, "qty": 1])
cart.append(["name": "B", "price": 4.99, "qty": 2])

UserDefaults.standard.set(cart, forKey: "myCart")

if let loadedCart = UserDefaults.standard.array(forKey: "myCart") as? [[String: Any]] {
print(loadedCart) // [[price: 19.99, qty: 1, name: A], [price: 4.99, qty: 2, name: B]]"
for item in loadedCart {
print(item["name"] as! String) // A, B
print(item["price"] as! Double) // 19.99, 4.99
print(item["qty"] as! Int) // 1, 2
}
}


您只需更改声明字典数组的方式。您应该使用 [String: AnyObject] 而不是 [String: Any]。你应该这样做:

swift 2.3

var cart: [[String: AnyObject]] = []
cart.append(["name": "A", "price": 19.99, "qty": 1])
cart.append(["name": "B", "price": 4.99, "qty": 2])

NSUserDefaults().setObject(cart, forKey: "myCart")

if let loadedCart = NSUserDefaults().arrayForKey("myCart") as? [[String: AnyObject]] {
print(loadedCart) // [[price: 19.99, qty: 1, name: A], [price: 4.99, qty: 2, name: B]]"

for item in loadedCart {
print(item["name"] as! String) // A, B
print(item["price"] as! Double) // 19.99, 4.99
print(item["qty"] as! Int) // 1, 2
}
}

关于ios - Swift - 将字典数组保存到 NSUserDefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29555922/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com