Created
August 31, 2020 08:43
-
-
Save 1024jp/3d59eb9651944022ad2c9dc88f6022ee 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
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