如何定义一个包含枚举的协议,它包含自己定义的值,其中一个存储为属性?

时间:2016-04-20 10:39:46

标签: 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

}

2 个答案:

答案 0 :(得分:6)

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
}

答案 1 :(得分:-2)

enum继承的协议示例

   protocol validator{

        var id : String{ get }
    }

    enum testEnum: validator{
        case african
        case european
        case unknown

        var id: String{

            return self.getDescription()
        }
        func getDescription() -> String{
            switch self {
            case .african:
                return "African"
            case .european:
                return "European"
            default:
                return "Unknown"

            }
        }
    }

    var c = testEnum.african
    let cDescription = c.id