-
-
Save vladimir-bebeshko/0eb4c388f77d63de17fb678ad9c941c3 to your computer and use it in GitHub Desktop.
Nested property wrappers with Swift
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
// https://noahgilmore.com/blog/nesting-property-wrappers | |
import Cocoa | |
protocol Appendable { | |
func appending(string: String) -> Self | |
} | |
extension String: Appendable { | |
func appending(string: String) -> String { | |
return self + string | |
} | |
} | |
@propertyWrapper | |
struct Appending<T: Appendable> { | |
private(set) var value: T | |
let toAppend: String | |
var wrappedValue: T { | |
get { value } | |
set { value = newValue.appending(string: toAppend) } | |
} | |
init(wrappedValue: T, _ toAppend: String) { | |
self.value = wrappedValue | |
self.toAppend = toAppend | |
} | |
} | |
extension Appending: Appendable { | |
func appending(string: String) -> Appending<T> { | |
return Appending(wrappedValue: self.wrappedValue.appending(string: string), self.toAppend) | |
} | |
} | |
struct Test { | |
@Appending("!") | |
@Appending("?") | |
var name: String = "" | |
init(_ name: String) { | |
self.name = name | |
} | |
} | |
var a = Test("Noah") | |
print(a.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment