Skip to content

Instantly share code, notes, and snippets.

@norio-nomura
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save norio-nomura/efd754a70885a4025d08 to your computer and use it in GitHub Desktop.
Save norio-nomura/efd754a70885a4025d08 to your computer and use it in GitHub Desktop.
enumCast()
import Foundation
func enumCast<C1, C2: RawRepresentable where C2.RawValue == C1>(rawValue: C1?) -> C2? {
if let rawValue = rawValue {
return C2(rawValue: rawValue)
} else {
return nil
}
}
func enumCast<C1, C2: RawRepresentable where C2.RawValue == C1>(rawValue: C1) -> C2? {
return C2(rawValue: rawValue)
}
// example
enum HogeFuga: String {
case Hoge = "hoge"
case Fuga = "fuga"
}
var s: String?
s = "hoge"
// using enumCast()
if let hogefuga: HogeFuga = enumCast(s) {
println(hogefuga)
} else {
println("err")
}
// without enumCast()
if let s = s {
if let hogefuga = HogeFuga(rawValue: s) {
println(hogefuga)
} else {
println("err")
}
} else {
println("err")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment