gpt4 book ai didi

uiimage - 如何使 UIImage 符合 Codable?

转载 作者:行者123 更新时间:2023-12-03 14:35:36 31 4
gpt4 key购买 nike

Swift 4 有 Codable这太棒了。但是UIImage默认情况下不符合它。我们怎么能做到这一点?

我试过 singleValueContainerunkeyedContainer

extension UIImage: Codable {
// 'required' initializer must be declared directly in class 'UIImage' (not in an extension)
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let data = try container.decode(Data.self)
guard let image = UIImage(data: data) else {
throw MyError.decodingFailed
}

// A non-failable initializer cannot delegate to failable initializer 'init(data:)' written with 'init?'
self.init(data: data)
}

public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
guard let data = UIImagePNGRepresentation(self) else {
return
}

try container.encode(data)
}
}

我收到 2 个错误
  • “必需”初始化程序必须直接在类“UIImage”中声明(而不是在扩展中)
  • 不可失败的初始化程序不能委托(delegate)给用“init?”编写的可失败初始化程序“init(data:)”

  • 一种解决方法是使用包装器。但是还有其他方法吗?

    最佳答案

    最简单的方法就是让它 Data而不是 UIImage :

    public struct SomeImage: Codable {

    public let photo: Data

    public init(photo: UIImage) {
    self.photo = photo.pngData()!
    }
    }
    反序列化图像:
    UIImage(data: instanceOfSomeImage.photo)!

    关于uiimage - 如何使 UIImage 符合 Codable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46197785/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com