当前位置:网站首页>Use of swift basic codable (jsonencoder jsondecoder)
Use of swift basic codable (jsonencoder jsondecoder)
2022-07-25 19:13:00 【Feng Hanxu】
I always feel that what I write is not technology , But feelings , One tutorial after another is the trace of one's own journey . Success with expertise is the most replicable , I hope my path will make you less detours , I hope I can help you erase the dust of knowledge , I hope I can help you clarify the context of knowledge , I hope there will be you and me on the top of technology in the future .
Preface
Codable The use of is generally used to store the data of the model , The model passes before storage Codable convert to data, Then take it out and pass data Convert to the corresponding model ,2. Add the use of route jump controller to change the model from A The controller is passed to B controller . It needs to be converted into binary . Restore the model after passing it back
On the subject
Use Codable Model of , The model needs to be followed Codable agreement .
If the model is nested with the model , Every model should also follow Codable agreement
for instance :

import Foundation
enum TimelineMediaType: Int, Codable {
case unknown
case images
case video
}

import Foundation
public enum UserStatus: Int, Codable {
case none = 0 // Unknown
case free = 1 // Free
case calling = 2 // Talking about
case resting = 3 // Don't disturb
case hide = 4 // stealth
case offline = 6 // offline
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 " Free "
case .calling: return " Talking about "
case .resting: return " Don't disturb "
case .hide: return " stealth "
case .offline: return " offline "
}
}
}

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
}
}
Use :
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))")
}
Print the results :
timelineDetailType: Optional(SwiftDemol.TimelineMediaType.images)
onlineState: Optional(SwiftDemol.UserStatus.calling)
title: Optional("fenghanxu")
cache: Optional(SwiftDemol.GreetingSelectionCache(textID: 1, voiceID: 2, pictureID: 3))
边栏推荐
- [open source project] stm32c8t6 + ADC signal acquisition + OLED waveform display
- JS 基本类型 引用类型 深/浅克隆复制
- ThreadLocal Kills 11 consecutive questions
- Weak network test tool -qnet
- The second "future Cup" knowledge map championship was officially launched
- srec_cat 常用参数的使用
- Common development software download addresses
- Pymoo learning (5): convergence analysis
- Alibaba cloud free SSL certificate application detailed process
- Intouch高级报警(报警筛选)
猜你喜欢

Fruit chain "siege": it's a journey of sweetness and bitterness next to apples

HTTP缓存通天篇,可能有你想要的

Common development software download addresses

Care for front-line epidemic prevention workers, Haocheng JIAYE and Gaomidian sub district office jointly build the great wall of public welfare

阿里云技术专家郝晨栋:云上可观测能力——问题的发现与定位实践

聊聊接口性能优化的11个小技巧

怎样设计产品帮助中心?以下几点不可忽视

2022 IAA industry category development insight series report - phase II

ThreadLocal Kills 11 consecutive questions

房企打响“保交战”
随机推荐
Telnet installation and telnet (correct password) cannot log in!
How to change the chords after the tune of the song is changed
[iniparser] simple use of the project configuration tool iniparser
[cloud native kubernetes] management of secret storage objects under kubernetes cluster
Pymoo学习 (8):Gradients
【加密周报】加密市场有所回温?寒冬仍未解冻!盘点上周加密市场发生的重大事件!
[applet development] do you know about applet development?
阿里云技术专家秦隆:可靠性保障必备——云上如何进行混沌工程?
基础乐理之音程的度数
无惧高温暴雨,有孚网络如何保您无忧?
Youwei low code: use resolutions
“未来杯”第二届知识图谱锦标赛正式启动
Huawei switch system software upgrade and security vulnerability repair tutorial
The difference between QT exec and show
HTTP缓存通天篇,可能有你想要的
srec_ Use of common cat parameters
600000 pieces of data are made from March 1 to March 31. Videodate requires starting time from 00:00 to 24:00 on March 1 to 31, which is only for notes
Pymoo学习 (5):收敛性分析
Care for front-line epidemic prevention workers, Haocheng JIAYE and Gaomidian sub district office jointly build the great wall of public welfare
网上商城系统MySql数据库设计项目实战