swift - 如何定义一个包含枚举的协议(protocol),该枚举具有它自己定义的值,并且其中一个值存储为属性?

标签 swift enums protocols

protocol TrackableAction {

    var identifier: String { get }

}

struct ServerAction: TrackableAction {

    let identifier = "Server"

    enum Label: String {

        case NotImplemented = "Feature not implemented"
        case NotPlanned = "Feature is not planned in this version"

    }

   var label: Label

}

struct ClientAction: TrackableAction {

    let identifier = "Client"

    enum Label: String {

        case NoneExisting = "Does not exist"
        case CannotFindRoot = "The root was unknown"

    }

   var label: Label

}

用法:

ServerAction(label: .NotImplemented)
ClientAction(label: .NoneExisting)

是否可以扩展 TrackableAction 以包含重复的枚举和标签定义?

我希望它能够将该类型的对象发送到函数

func log(trackableAction: TrackableAction) {
    // sends strings to a log service
    print(trackableAction.label) // ERROR

}

最佳答案

protocol TrackableAction {

    var identifier: String { get }
    var label: Label {get set}
    associatedtype Label: RawRepresentable
}

struct ServerAction: TrackableAction {

  let identifier = "Server"

  enum Label: String {

    case NotImplemented = "Feature not implemented"
    case NotPlanned = "Feature is not planned in this version"

  }

  var label: Label = Label.NotImplemented

}

func log<T: TrackableAction>(trackableAction: T) {
  // sends strings to a log service
  print(trackableAction.label) // ERROR
}

关于swift - 如何定义一个包含枚举的协议(protocol),该枚举具有它自己定义的值,并且其中一个值存储为属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36741286/

相关文章:

json - 如何从swift调用rest web服务

arrays - Swift - 来自 2 个过滤数组的字典

clang 枚举溢出

xcode - 使用枚举的默认实现扩展协议(protocol)会导致 Xcode 崩溃

arrays - fatal error - 在 for 循环中为数组赋值

ios - 双击栏按钮项目滚动到顶部

c++ - 具有固定值枚举器的枚举的零初始化

java - 用于依赖注入(inject)的类型安全枚举

protocols - super 终端使用什么通讯协议(protocol)?

swift - 更改 TableView 数据源时按钮不起作用?