WPK
WPK

Reputation: 402

Protocol extension default method causing a "self is immutable" error

I am trying to extend a class-bound protocol (UITextInputTraits) with a default method:

extension UITextInputTraits where Self: UIView {

    func setTextInputTraits() {

        self.autocapitalizationType = .none // <- compiler error
    }
}

It gives a "Cannot assign to property: 'self' is immutable" error.

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? How can I achieve implementing this default method?

Thank you!


Upvotes: 6

Views: 1952

Answers (1)

matt
matt

Reputation: 535944

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 {}

Upvotes: 2

Related Questions