使用Swift 4编写带浮点的结构

时间:2018-01-30 00:43:57

标签: swift struct codable

我有一个包含People(高度,年龄,性别)描述的结构。年龄是一个漂浮物,因为婴儿可以计算几个月(即:1.083年是13个月)。

我正在尝试将这些人的数组保存到用户默认值,但无法弄清楚如何使该类可编码。在类中是字符串,一个Float和一个Dictionary [String:String]。

建议?

STRUCT:

import Foundation

struct Person: Codable {
    var name: String
    var gender: String
    var age: Float
    var profilePictures: [String: String]

    init(name: String,
         gender: String,
         age: Float,
         profilePictures: [String: String])

    {
        self.name = name
        self.gender = gender
        self.age = age
        self.profilePictures = profilePictures
    }
}

我尝试将结果保存到用户默认值的类:

let defaults = UserDefaults.standard
defaults.set(self.people, forKey: "people") // Where self.people is an array of Person objects

1 个答案:

答案 0 :(得分:1)

您需要做的就是在解码数据时将一个人类型数组传递给json解码器。我建议不要将其保存到UserDefaults中,最好将数据写入json文件:

let person = Person(name: "devpreneur", gender: "male", age: 99, profilePictures: ["SO profile picture": "https://i.stack.imgur.com/Pz3pC.jpg"])
let people = [person]
do{
    let peopleData = try JSONEncoder().encode(people)
    // saving your people data
    let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let jsonURL = documentDirectory.appendingPathComponent("people.json")
    try peopleData.write(to: jsonURL, options: .atomic)

    // loading and decoding the json data
    let loadedData = try Data(contentsOf: jsonURL)
    let decodedPeople = try JSONDecoder().decode([Person].self, from: loadedData)
    for person in decodedPeople {
        print(person.name)
        print(person.gender)
        print(person.age)
        print(person.profilePictures)
    }
} catch { 
    print(error)
}