Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Created January 9, 2023 18:07
Show Gist options
  • Select an option

  • Save andresr-dev/dcf3ea31ad02a7a85d35f42790847069 to your computer and use it in GitHub Desktop.

Select an option

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
@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