STRUCT 数组到用户默认值

STRUCT 数组到用户默认值

问题描述:

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

I have a custom Struct class to hold calories, fats, carbs, and protein.

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

Each Time a user enters the data I put it into a variable

 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.

Now I also created an array to store everything. I then need to store all the values into array, which then store that to UserDefaults.

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

Then I will need to call the user defaults call array[0] lets say and then call each calorie, carb, ... something like thelog.calories // theology.carbs etc

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

To be able to use NSCoding the object must be a class. But as all values are property list compliant you could add a variable dictionaryRepresentation and a corresponding initializer.

首先从不在 Swift 中使用 NSMutableArray 并且从不 将变量声明为隐式解包可选,并使用非可选初始化器进行初始化.

First of all never use NSMutableArray in Swift and never declare variables as implicit unwrapped optional which are initialized with a non-optional initializer.

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]
    }
}

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

Now you can read the array from and write to user defaults.

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) }
}