Skip to content

Instantly share code, notes, and snippets.

@jayrhynas
Last active February 22, 2018 17:26
Show Gist options
  • Save jayrhynas/08591b8728baa5a4fded52f5d5aa8956 to your computer and use it in GitHub Desktop.
Save jayrhynas/08591b8728baa5a4fded52f5d5aa8956 to your computer and use it in GitHub Desktop.
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