【问题标题】:Issue with making a Class with an enum Conform to Codable Protocol使用符合可编码协议的枚举创建类的问题
【发布时间】:2020-11-11 08:04:46
【问题描述】:

我是 IOS 开发的新手,我正在尝试创建一个应用程序,其中轮子旋转并随机停止在某个点,以将信息推送到用户默认值中,我需要解码自定义对象。但是,当我尝试使类“可编码”时,它给了我错误不符合协议。

如果我删除它可以工作的枚举,但我需要枚举来为每个单独的选择设置颜色,有没有办法使这个 Codable ?

TTFortuneWheel 是我安装的Pod 以协助旋转动画。

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
    }
    

}

【问题讨论】:

  • 枚举样式:字符串会起作用
  • 不相关,但您可以通过直接关联十六进制值(作为整数或字符串)来简化代码:enum Style: Int, Codable & case blue = 0xdff9fb...

标签: swift enums codable


【解决方案1】:

如果您希望可编码类的每个属性都能自动工作(也就是说,不定义自定义 init(from:)encode(to:) 方法),则它本身必须是可编码的。

问题是var style: StyleStyle 不可编码。最简单的方法是使其成为基于字符串的枚举

enum Style: String, Codable

如果你这样做,例如,你的类将被编码为 JSON,并带有这样的字段

"style": "green" 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多