Last active
August 29, 2015 14:14
-
-
Save norio-nomura/efd754a70885a4025d08 to your computer and use it in GitHub Desktop.
enumCast()
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
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