Last active
February 22, 2018 17:26
-
-
Save jayrhynas/08591b8728baa5a4fded52f5d5aa8956 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
protocol Wrapper { | |
associatedtype Value | |
var value: Value { get set } | |
init(value: Value) | |
init(_ value: Value) | |
func unwrap() -> Value | |
} | |
extension Wrapper { | |
init(_ value: Value) { | |
self.init(value: value) | |
} | |
func unwrap() -> Value { | |
return self.value | |
} | |
} | |
// doesn't work | |
/* | |
extension Wrapper.Value { | |
init(_ wrapped: Wrapper) { | |
self = wrapped.value | |
} | |
} | |
*/ | |
// works, but is clunky | |
protocol WrappedValue { | |
associatedtype Parent: Wrapper | |
init(_ wrapper: Parent) | |
} | |
extension WrappedValue where Parent.Value == Self { | |
init(_ wrapper: Parent) { | |
self = wrapper.value | |
} | |
} | |
// Tests | |
struct IntWrapper: Wrapper { | |
var value: Int = 0 | |
} | |
extension Int: WrappedValue { | |
typealias Parent = IntWrapper | |
} | |
let one = IntWrapper(1) | |
print(one.unwrap()) | |
print(Int(one)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment