I have a recursive enumeration where most cases have the same types of related values:
indirect enum Location {
case Title(String?)
case Region(Location)
case Area(Location, Location)
case City(Location, Location)
case Settlement(Location, Location)
case Street(Location, Location)
case House(Location, Location)
}
What I want to do is create a beautiful string description that will include all non-nil captions.
func getStringFromLocation(location: Location) -> String? {
var parts: [String?] = []
switch location {
case .Title(let title): return title
case .House(let title, let parent):
parts.append(getStringFromLocation(parent))
parts.append(getStringFromLocation(title))
case .Street(let title, let parent):
parts.append(getStringFromLocation(parent))
parts.append(getStringFromLocation(title))
case .Settlement(let title, let parent):
parts.append(getStringFromLocation(parent))
parts.append(getStringFromLocation(title))
case .City(let title, let parent):
parts.append(getStringFromLocation(parent))
parts.append(getStringFromLocation(title))
case .Area(let title, let parent):
parts.append(getStringFromLocation(parent))
parts.append(getStringFromLocation(title))
case .Region(let title):
parts.append(getStringFromLocation(title))
}
return parts
.filter { $0 != nil }
.map { $0! }
.joinWithSeparator(", ")
}
The problem is that five of the seven possible cases are the same, and I have a bunch of copied code, which I believe is not very good. What if I have a list of hundreds of cases?
Is there a way to write something like this?
switch location {
case .Title(let title):
parts.append(title)
case .Region(let title):
parts.append(getStringFromLocation(title))
default (let title, let parent):
parts.append(getStringFromLocation(parent))
parts.append(getStringFromLocation(title))
}
... using some default case to handle all such cases?
source
share