当前位置:网站首页>[Swift]对自定义对象添加复制功能
[Swift]对自定义对象添加复制功能
2022-08-07 02:58:00 【风浅月明】
使用复制功能
let lisi = DMObject()
lisi.name = "李四"
lisi.age = "20"
lisi.classify = .live
let copyLisi = lisi.copyObject()
让需要实现解归档的类遵循CustomCodable协议
import UIKit
public enum DMClassify: Int, CustomCodable {
case home = 100
case live = 101
}
class DMObject: NSObject, CustomCodable {
var name : String?
var age : String?
var classify : DMClassify?
}
自定义CustomCodable继承Codable协议(Codable其实就是Decodable和Encodable)
import UIKit
protocol CustomCodable: Codable {
func copyObject() -> Self
}
extension CustomCodable {
func copyObject() -> Self {
let encoder = JSONEncoder()
guard let data = try? encoder.encode(self) else {
fatalError("encode failed")
}
let decoder = JSONDecoder()
guard let target = try? decoder.decode(Self.self, from: data) else {
fatalError("decode failed")
}
return target
}
}
边栏推荐
猜你喜欢

xcode armv6 armv7 armv7s arm64

Remember a common performance optimization process for To B development... report optimization

How to smoothly render tens of millions of 2D objects with WebGPU: based on the ray tracing line

STM32——RTC实时时钟原理+BKP寄存器原理

什么是传输网、核心网、承载网、接入网?

一夜成名的航班追踪网站,什么来头?

web漏洞扫描器-Burpsuite 常规测试

多种方法对建模数据做特征选择

haproxy实验

Coco data set analysis and reading method
随机推荐
大型网站高并发解决方案——集群
解决[__NSArrayM objectAtIndex:]: index 0 beyon Objective-C异常Bug方法
基于STM32F103C8T6最小系统板驱动灰度模块进行循迹
投稿经验分享之三:SCI投稿之JEI录用
Large website high concurrency solution - cluster
STM32——RTC实时时钟原理+BKP寄存器原理
【FLink】Assigned key must not be null
Definition and operation process of OAuth2
redis持久化机制的理解
pycocotools库的使用
Getting Started with Tensorflow 2.0
【UGF】GameFramework接入HybridCLR(wolong)卧龙热更框架
How to smoothly render tens of millions of 2D objects with WebGPU: based on the ray tracing line
The main reasons and solutions for optical module failures
PyG搭建R-GCN实现链接预测
js 实现两个小数的相乘、相除、相加和相减功能
LVS load balancing cluster
[Verilog Basics] Some basic concepts of DFT (Design for Test) testability design
什么是传输网、核心网、承载网、接入网?
6-8 求二叉树高度(20分)