I'm trying to make UIFont
conform to Decodable
, but I'm having a hard time.
I currently have solution where im wrapping the UIFont in a Font struct like this
public struct Font: Decodable{
let font: UIFont
private enum CodingKeys: String, CodingKey {
case size
case font
}
public init(from decoder: Decoder){
do{
let values = try decoder.container(keyedBy: CodingKeys.self)
font = UIFont(name: try values.decode(String.self, forKey: .font), size: try values.decode(CGFloat.self, forKey: .size))!
} catch{
fatalError("Font configuration error:\(error)")
}
}
}
This works but I seems clumsy, so I was trying like this instead:
final class Font: UIFont, Decodable{
private enum CodingKeys: String, CodingKey {
case size
case font
}
convenience init(from decoder: Decoder) {
do{
let values = try decoder.container(keyedBy: CodingKeys.self)
super.init(name: try values.decode(String.self, forKey: .font), size: try values.decode(CGFloat.self, forKey: .size))
} catch{
fatalError("Font configuration error:\(error)")
}
}
}
This however do not work because init(from decoder: Decoder)
can not be a failable initialiser and UIFont.init(name: String, size: CGFloat)
is a failable initialiser, and calling a failable init from a non failable one is not possible.
Any suggestions to how to make UIFont
conform to Decodable
without wrapping it is highly appreciated.