【问题标题】:Making a Struct with a Float encodable with Swift 4使用 Swift 4 制作带有浮点数的结构
【发布时间】:2018-01-30 00:43:56
【问题描述】:

我有一个包含 People 描述(身高、年龄、性别)的结构。年龄是一个浮点数,因为它可以以婴儿的月数来计算(即:1.083 岁是 13 个月)。

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

建议?

结构:

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

【问题讨论】:

  • 您遇到什么错误?它的编译错误吗?运行时错误?
  • 添加错误 - 谢谢
  • @devpreneur UserDefaults 并不是为了保存 App 数据。最好将您的应用数据保存到常规的 json 文件中。检查此答案以获得更好的位置来保存仅适用于您的应用程序的应用程序数据stackoverflow.com/questions/34701630/…
  • 我建议你也看看文件系统基础文档developer.apple.com/library/content/documentation/…
  • 谢谢,会去阅读这两篇#learning

标签: swift struct codable


【解决方案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)
}

【讨论】:

  • 效果很好!得到它写入和阅读本地副本。非常感谢您快速详细的回复。
猜你喜欢
  • 2018-06-08
  • 1970-01-01
  • 2019-01-21
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
  • 2018-05-11
  • 1970-01-01
  • 2018-01-10
相关资源
最近更新 更多