Created
October 27, 2015 20:15
-
-
Save designatednerd/5645d286df0ce939714b to your computer and use it in GitHub Desktop.
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
/** | |
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