Skip to content

Instantly share code, notes, and snippets.

@boylee1111
Created April 3, 2015 10:25
Show Gist options
  • Save boylee1111/ff2ad3dcb0a69b92adb4 to your computer and use it in GitHub Desktop.
Save boylee1111/ff2ad3dcb0a69b92adb4 to your computer and use it in GitHub Desktop.
A Swift Tour. Write an enumeration that conforms to this protocol.
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
enum SimpleEnum : String, ExampleProtocol {
case Before = "", After = " (whatever)"
var simpleDescription: String {
get {
return "A simple enum." + self.rawValue
}
}
mutating func adjust() {
self = .After
}
}
var c = SimpleEnum.Before
c.adjust()
c.simpleDescription
@tempelmann
Copy link

Just googled for the exercise and found this.

Your solution modifies the enum's value. Which is just fine, but I wanted to show others an alternative:

Based on this gist I came up with this which keeps the Enum value and instead changes its associated values:

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)

@iDevSpread
Copy link

Hi, I typed your code but Xcode(8.3.2) gave me a compiler error for raw type error. The codes in the following are modified according to your codes.

enum SimpleEnumeration: ExampleProtocol {
	case Before, After
	var simpleDescription: String {
		get {
		    return "A simple enum."
		}
	}
	
	mutating func adjust() {
		self = .After
	}

}

var c = SimpleEnumeration.Before
a.adjust()
c.simpleDescription

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