Created
June 4, 2014 05:03
-
-
Save anonymous/5cc0af9ba0e94434d295 to your computer and use it in GitHub Desktop.
Possible Solution for Swift Enum conforming to a protocol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
I am not exacly sure, how a conforming enum would look like.
I tried:
enum SimpleEnum: String {
case simpleDescription = "A simple enum type."
func adjust() ->String {
return self.toRaw() + " - finally adjusted"
}
}
var myEnum = SimpleEnum.simpleDescription
let descr = myEnum.adjust()
because my understanding from reading the book was, that you only can use the expression after the collon as associated value. But probaby my solution is not conform to the protocol
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
Or, as a self-contained enumeration using associated values: