一直觉得自己写的不是技术,而是情怀,一个个的教程是自己这一路走来的痕迹。靠专业技能的成功是最具可复制性的,希望我的这条路能让你们少走弯路,希望我能帮你们抹去知识的蒙尘,希望我能帮你们理清知识的脉络,希望未来技术之巅上有你们也有我。
前言
Codable的使用一般用于存储模型的数据,模型在存储前通过Codable转换成data,然后取出来之后通过data转换成对应的模型,2.加入使用路由跳转控制器把模型从A控制器传递到B控制器。需要先转换成二进制。传递过去之后把模型还原回来
正题
使用Codable的模型,模型需要遵守Codable协议。
如果模型嵌套模型,每个模型也要遵守Codable协议
举个例子:
import Foundation
enum TimelineMediaType: Int, Codable {
case unknown
case images
case video
}
import Foundation
public enum UserStatus: Int, Codable {
case none = 0 // 未知
case free = 1 // 空闲
case calling = 2 // 在聊
case resting = 3 // 勿扰
case hide = 4 // 隐身
case offline = 6 // 离线
public static func fromInt(_ value: Int) -> UserStatus {
switch value {
case 1: return .free
case 2: return .calling
case 3: return .resting
case 4, 5: return .hide
case 6, 7: return .offline
default: return .none
}
}
public var description: String {
switch self {
case .none: return ""
case .free: return "空闲"
case .calling: return "在聊"
case .resting: return "勿扰"
case .hide: return "隐身"
case .offline: return "离线"
}
}
}
import Foundation
struct GreetingSelectionCache: Codable {
var textID: Int64 = 0
var voiceID: Int64 = 0
var pictureID: Int64 = 0
}
import Foundation
class TimelineDetailModel: Codable {
var timelineDetailType: TimelineMediaType
var onlineState: UserStatus
var title: String
var cache: GreetingSelectionCache
init(
_ timelineDetailType: TimelineMediaType = .unknown,
_ onlineState: UserStatus = .none,
_ title: String = "",
_ cache: GreetingSelectionCache = GreetingSelectionCache(textID: 0, voiceID: 0, pictureID: 0)
) {
self.timelineDetailType = timelineDetailType
self.onlineState = onlineState
self.title = title
self.cache = cache
}
}
使用:
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let JSONEncoderModel = TimelineDetailModel()
JSONEncoderModel.timelineDetailType = .images
JSONEncoderModel.onlineState = .calling
JSONEncoderModel.title = "fenghanxu"
let cache = GreetingSelectionCache(textID: 1, voiceID: 2, pictureID: 3)
JSONEncoderModel.cache = cache
guard let data = try? JSONEncoder().encode(JSONEncoderModel) else { return }
let JSONDecoderModel = try? JSONDecoder().decode(TimelineDetailModel.self, from: data)
print("timelineDetailType: \(String(describing: JSONDecoderModel?.timelineDetailType))")
print("onlineState: \(String(describing: JSONDecoderModel?.onlineState))")
print("title: \(String(describing: JSONDecoderModel?.title))")
print("cache: \(String(describing: JSONDecoderModel?.cache))")
}
打印结果:
timelineDetailType: Optional(SwiftDemol.TimelineMediaType.images)
onlineState: Optional(SwiftDemol.UserStatus.calling)
title: Optional("fenghanxu")
cache: Optional(SwiftDemol.GreetingSelectionCache(textID: 1, voiceID: 2, pictureID: 3))
版权声明:本文为weixin_38716347原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。