Jacob King Jacob King - 1 month ago 11
Swift Question

Swift - extend an enum for only one of it's cases

So I have an enum that controls an instance of a view controller as well as the creation of said view controller. See below:

enum RGOSessionsTableType {
case Active
case Scheduled
case Finished

func instantiateViewController() -> RGOSessionsTableViewController {
var id = ""
switch self {
case .Active: id = "ActiveSessionsTVC"
case .Scheduled: id = "ScheduledSessionsTVC"
case .Finished: id = "FinishedSessionsTVC"
}
return UIStoryboard(name: "MainView", bundle: nil).instantiateViewControllerWithIdentifier(id) as! RGOSessionsTableViewController
}
}


I want to create a property on that enum that stores the instantiated view controller, however for reasons I won't explain (mainly ease of integration with existing code), I wish to use the specific class types for Active, Scheduled and Finished respectively. They all inheirit from
RGOSessionsViewController
but as I mentioned I would rather not make the property of this lower level type.

I have tried the following which will not compile, I have never done where clauses on extensions before so it is likely I have the syntax wrong, that or it simply isnt possible:

extension RGOSessionsTableType where self == .Active {

}


Any and all suggestions appreciated.

Answer

Moved from comments:

I think here enum is not a best idea. You should try to do this with protocol + 3 classes/structs implementing it. That will allow you both extend "only one case" and add more "cases" in it. Like here.

Quick info about linked article:

Why I don’t love Swift Enums any more

At the last two Sydney Cocoaheads, any time I see a use of Enums in a talk, I make sure to ask “Why an enum and not a protocol?”. This blog post will hopefully explain the smell of enums.


Firstly, I have to say that enums are great if you never need to extend the number of cases. However, incorrect usages of enums break the O in SOLID Principles.

Open Close Principle

A Type should be open to extension, but closed for edits.

And I believe the Expression Problem best explains the violation.

The Expression Problem

Add new methods; add new cases. Pick one.

I will attempt to walk you through the Expression Problem with enums, then proceed to “solve” it with the Visitor Pattern.