gpt4 book ai didi

swift - STRUCT 数组到 UserDefaults

转载 作者:搜寻专家 更新时间:2023-11-01 07:14:45 25 4
gpt4 key购买 nike

我有一个自定义的 Struct 类来保存卡路里、脂肪、碳水化合物和蛋白质。

每次用户输入数据时,我都会将其放入变量中

 var theArray : NSMutableArray = []

struct CFCPstruct {
let calories : Int!
let fats : Int!
let carbs : Int!
let protein: Int!
init(Calories: Int, Fats: Int, Carbs: Int, Protein: Int) {
self.calories = Calories
self.fats = Fats
self.carbs = Carbs
self.protein = Protein
}
}

let addLog = [CFCPstruct(Calories: totalCalories, Fats: totalFats, Carbs: totalCarbs, Protein: totalProtein)]

现在我还创建了一个数组来存储所有内容。然后我需要将所有值存储到数组中,然后将其存储到 UserDefaults。

然后我需要调用用户默认值调用数组 [0] 让我们说然后调用每个卡路里、碳水化合物...类似 thelog.calories//theology.carbs 等

最佳答案

为了能够使用NSCoding,对象必须是一个类。但由于所有值都符合属性列表,您可以添加变量 dictionaryRepresentation 和相应的初始化器。

首先,从不在 Swift 中使用 NSMutableArray 并且从不将变量声明为隐式展开的可选变量,这些变量是使用非可选初始化程序初始化的。

var theArray = [CFCPstruct]()

struct CFCPstruct {
let calories : Int
let fats : Int
let carbs : Int
let protein: Int

init(calories: Int, fats: Int, carbs: Int, protein: Int) {
self.calories = calories
self.fats = fats
self.carbs = carbs
self.protein = protein
}

init(dictionary : [String:Int]) {
self.calories = dictionary["calories"]!
self.fats = dictionary["fats"]!
self.carbs = dictionary["carbs"]!
self.protein = dictionary["protein"]!
}

var dictionaryRepresentation : [String:Int] {
return ["calories" : calories, "fats" : fats, "carbs" : carbs, "protein" : protein]
}
}

现在您可以读取和写入用户默认值的数组。

func saveDefaults() 
{
let cfcpArray = theArray.map{ $0.dictionaryRepresentation }
UserDefaults.standard.set(cfcpArray, forKey: "cfcpArray")
}

func loadDefaults()
{
theArray = (UserDefaults.standard.object(forKey: "cfcpArray") as! [[String:Int]]).map{ CFCPstruct(dictionary:$0) }
}

关于swift - STRUCT 数组到 UserDefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42777752/

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