I am trying to extend a class-bound protocol (
UITextInputTraits
extension UITextInputTraits where Self: UIView {
func setTextInputTraits() {
self.autocapitalizationType = .none // <- compiler error
}
}
"Cannot assign to property: 'self' is immutable"
UIView
UITextField
mutating
'mutating' isn't valid on methods in classes or class-bound protocols
perform
func setTextInputTraits() {
let sel = #selector(setter: self.autocapitalizationType)
self.perform(sel, with: .none)
}
It works if I change the constraint from UIView to UITextField though, but that defeats the purpose of using protocols. Why is it an error?
Because UIView doesn't already have an autocapitalizationType
property. Thus, the compiler has no reason to believe that if it did have one, it would be settable.
How can I achieve implementing this default method?
I think you might be after something like this:
protocol MyTextInputTraits : UITextInputTraits {
var autocapitalizationType: UITextAutocapitalizationType {get set}
}
extension MyTextInputTraits {
func setTextInputTraits() {
self.autocapitalizationType = .none
}
}
extension UITextView : MyTextInputTraits {}
extension UITextField : MyTextInputTraits {}
extension UISearchBar : MyTextInputTraits {}