Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
How to get a method which takes any string enumeration in Swift 2.1.
Actually figured out by Carl Hill-Popper, documented by me.
*/
import UIKit
// 1) Make you some string enums.
enum Wat: String {
case
O,
Hai,
Wut
}
enum Something: String {
case
Boop,
Bleep,
Blorp
}
// 2) Make a protocol which matches the features of the enum you need to use.
protocol StringEnum {
var rawValue: String { get }
}
// 3) Pretending these are in machine-generated files and you can't access them
// directly to add the protocol, add the protocol using an extension.
extension Wat: StringEnum {
//Don't actually do anything since this already conforms
//because a Wat: String already returns a rawValue.
}
extension Something: StringEnum {
//Don't actually do anything since this already conforms
//because a Something: String already returns a rawValue.
}
// 4) do something which takes anything conforming to the string
func doAThingWithAStringEnum(coreDataKey: StringEnum) -> String {
return coreDataKey.rawValue
}
print(doAThingWithAStringEnum(Wat.Hai))
// Prints "Hai"
print(doAThingWithAStringEnum(Something.Bleep))
// Prints "Bleep"
// 5) Have a 🍺 to celebrate passing arbitrary string enums to a centralized method.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment