Skip to content

Instantly share code, notes, and snippets.

Created June 4, 2014 05:03
Show Gist options
  • Save anonymous/5cc0af9ba0e94434d295 to your computer and use it in GitHub Desktop.
Save anonymous/5cc0af9ba0e94434d295 to your computer and use it in GitHub Desktop.
Possible Solution for Swift Enum conforming to a protocol
enum testEnum: ExampleProtocol{
case a, b, c
var simpleDescription: String{
get{
return "an example enum"
}
set {
simpleDescription = newValue
}
}
mutating func adjust() {
simpleDescription += " (whatever)"
}
}
var protoEnum = testEnum.a
let test = protoEnum.simpleDescription
@tempelmann
Copy link

Here's how I solved it based on kasei's code:

enum ServerResponse: ExampleProtocol {
    case Result(String, String)
    case Error(String)
    var simpleDescription: String {
        get {
            switch self {
            case let .Result(sunrise, sunset):
                return "Sunrise is at \(sunrise) and sunset is at \(sunset)."
            case let .Error(error):
                return "Failure...  \(error)"
            }
        }
    }
    mutating func adjust() {
        switch self {
            case Result(let v1, let v2):
                self = Result(v1 + " (adjusted)", v2 + " (adjusted)")
            case Error(let v1):
                self = Error(v1 + " (adjusted)")
        }
    }
}

var success = ServerResponse.Result("6:00 am", "8:09 pm")
var failure = ServerResponse.Error("Out of cheese.")
success.adjust()
failure.adjust()
print(success.simpleDescription)
print(failure.simpleDescription)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment