Created
January 9, 2023 18:07
-
-
Save andresr-dev/dcf3ea31ad02a7a85d35f42790847069 to your computer and use it in GitHub Desktop.
This is an example of how to use the propertyWrapper attribute to autocapitalize strings in swift
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
| @propertyWrapper | |
| struct Capitalized { | |
| var wrappedValue: String { | |
| didSet { wrappedValue = wrappedValue.capitalized } | |
| } | |
| init(wrappedValue: String) { | |
| // we need to explicitly capitalize any string that was passed into our initializer | |
| // since property observers are only triggered after a value or object was fully initialized. | |
| self.wrappedValue = wrappedValue.capitalized | |
| } | |
| } | |
| struct User { | |
| @Capitalized var firstName: String | |
| @Capitalized var lastName: String | |
| } | |
| let andres = User(firstName: "andres", lastName: "raigoza") | |
| print(andres.firstName) // Andres | |
| print(andres.lastName) // Raigoza |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment