使用Codable(Swift)从Json文件解析UIColor

编程入门 行业动态 更新时间:2024-10-05 09:24:56
本文介绍了使用Codable(Swift)从Json文件解析UIColor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试解码json文件,并且我在那里有很多ui配置,我正在寻找一种干净的解决方案以直接将十六进制代码解析为UIColor。但是UIColor不符合Codable。

Im trying to decode a json file, and i have alot of ui configurations there, and im looking for a clean solution to parse directly a hex code to UIColor. But UIColor doesnt conform to Codable.

例如,此json:

var json = """ { "color": "#ffb80c" } """.data(using: .utf8)!

而我希望能够做到这一点:

and i want to be able to do this:

struct Settings: Decodable { var color: UIColor }

,而即时解码将十六进制字符串转换为UIColor

and while im decoding convert the "hex" string into a UIColor

我已经具有此功能,可以从字符串中解码并返回UIColor:

I already have this function to decode from a String and return a UIColor:

public extension KeyedDecodingContainer { public func decode(_ type: UIColor.Type, forKey key: Key) throws -> UIColor { let colorHexString = try self.decode(String.self, forKey: key) let color = UIColor(hexString: colorHexString) return color } }

要执行此操作,我需要通过手动解码容器并对其进行解码,但是由于我有很多配置,因此我的课程非常庞大,因为我需要设置所有内容:

For this to work i need to decode it manually by getting the container and decode it, but since i have alot of configurations my class will be huge because i need to set everything:

struct Settings: Decodable { var color: Color enum CodingKeys: CodingKey { case color } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) color = try container.decode(UIColor.self, forKey: .color) } }

最终im寻找一种更清洁的方法来执行此操作。理想的方法是将UIColor设置为可编码(但我认为我不能做到这一点)

In the end im looking for a much cleaner way to do this. The ideal way is to turn UIColor codable (but i think i cant do that)

预先感谢

推荐答案

我要解决此问题的方法是引入一种新的 Color 类型,该类型符合 Decodable 协议并包装单个 UIColor 属性:

What I did to solve this problem is to introduce a new Color type that conforms to the Decodable protocol and wraps a single UIColor property:

struct Color : Decodable { let value: UIColor init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let string = try container.decode(String.self) self.value = try UIColor(rgba_throws: string) // From github/yeahdongcn/UIColor-Hex-Swift } }

然后您将使用它:

cell.textLabel?.textColor = settings.color.value

仅适用于UIColor,如果您希望使其适用于不符合Decoda的任何类型作为一种协议,John Sundell在在Swift中自定义可编码类型中描述了一种通用方法。

That's for UIColor only, if you want to make it work for any type that doesn't conform to the Decodable protocol, John Sundell describes a generic approach in Customizing Codable types in Swift.

更多推荐

使用Codable(Swift)从Json文件解析UIColor

本文发布于:2023-11-26 23:25:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635636.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   Swift   Codable   UIColor   Json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!