Limit characters in a Form using @Binding - SwiftUI

We can accomplish the task by using a Binding extension like so:

extension Binding where Value == String {
    func max(_ limit: Int) -> Self {
        if self.wrappedValue.count > limit {
            DispatchQueue.main.async {
                self.wrappedValue = String(self.wrappedValue.dropLast())
            }
        }
        return self
    }
}

and this is how you would use it:

struct DemoView: View {
    @State private var textField = ""
    var body: some View {
        TextField("8 Char Limit", text: self.$textField.max(8)) // Here
            .padding()
    }
}

This is extremely useful for validating a user form.

Sources: 1

With love and respect,
Arturo 👨🏻‍💻