Skip to content

Instantly share code, notes, and snippets.

@1024jp
Created August 31, 2020 08:43
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 1024jp/3d59eb9651944022ad2c9dc88f6022ee to your computer and use it in GitHub Desktop.
Save 1024jp/3d59eb9651944022ad2c9dc88f6022ee to your computer and use it in GitHub Desktop.
enum DogCow: Int {
case dog, cow
}
struct Wrapper<Value> {
func newValue(from value: Any?) -> Value? {
return value as? Value ?? Optional<Any>.none as? Value
}
func newValue(from value: Any?) -> Value? where Value: RawRepresentable {
return (value as? Value.RawValue).flatMap(Value.init)
}
}
let int = Wrapper<Int>()
let dogCow = Wrapper<DogCow>()
// what I want
int.newValue(from: 0) // -> 0
dogCow.newValue(from: 0) // -> DogCow.dog
func foo<Value>(_ wrapper: Wrapper<Value>, value: Any, type: Any.Type? = nil) -> Value? {
return wrapper.newValue(from: value)
}
let bar = type(of: dogCow)
foo(dogCow, value: 0) // -> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment