[英]Issue with making a Class with an enum Conform to Codable Protocol
我是 IOS 開發的新手,我正在嘗試創建一個應用程序,其中輪子旋轉並隨機停止在某個點,將信息推送到用戶默認值中,我需要解碼自定義 object。 但是,當我嘗試使 class 'Codable' 時,它給了我錯誤不符合協議。
如果我刪除它可以工作的枚舉,但我需要枚舉來為每個單獨的選擇設置顏色,有沒有辦法讓這個 Codable?
TTFortuneWheel
是我安裝的Pod
,用於協助旋轉 animation。
import UIKit
import TTFortuneWheel
class CarnivalWheel: FortuneWheelSliceProtocol, Codable {
enum Style {
case blue
case purple
case green
case grey
case orange
case yellow
}
var style: Style = .blue
var backgroundColor: UIColor? {
switch style {
case .blue: return TTUtils.uiColor(from: 0xdff9fb)
case .purple: return TTUtils.uiColor(from: 0xa29bfe)
case .green: return TTUtils.uiColor(from: 0x7bed9f)
case . grey: return TTUtils.uiColor(from: 0xdfe4ea)
case .orange: return TTUtils.uiColor(from: 0xffbe76)
case .yellow: return TTUtils.uiColor(from: 0xf6e58d)
default: print("error getting colors")
}
}
var title: String
var degree: CGFloat = 0.0
init(title: String) {
self.title = title
}
var fontColor: UIColor {
return UIColor.black
}
var offsetFromExterior: CGFloat {
return 10.0
}
var stroke: StrokeInfo? {
return StrokeInfo(color: UIColor.white, width: 1.0)
}
convenience init(title: String, degree: CGFloat) {
self.init(title: title)
self.degree = degree
}
}
如果您希望可編碼 class 自動工作(即不定義自定義init(from:)
和encode(to:)
方法),可編碼 class 的每個屬性本身都需要可編碼。
問題是var style: Style
。 Style
不可編碼。 最簡單的方法是使其成為基於字符串的枚舉
enum Style: String, Codable
如果你這樣做,那么,例如,你的 class 將被編碼為 JSON 具有這樣的字段
"style": "green"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.