hakonbogen hakonbogen - 7 months ago 6
Swift Question

How to define a protocol that contains an enum with values it defines itself and one of them is stored as an attribute?

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

}


usage:

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


Is it possible to extend the TrackableAction to have the duplicated enum and label definition included?

I want this to be able to send objects of that type to a function

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

}

Answer
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
}