Gargoyle Gargoyle - 1 month ago 5x
Objective-C Question

Unable to set value via protocol

In my Objective C code I had this:

if ([view conformsToProtocol:@protocol(UITextInputTraits)]) {
id<UITextInputTraits> field = view;
field.enablesReturnKeyAutomatically = YES;

Now I'm trying to convert that to swift, so I did this:

if var field = view as? UITextInputTraits {
field.enabledReturnKeyAutomatically = true

I'm getting a compiler error saying that 'field' is immutable. What's the right way to accomplish this?


The problem is caused by Swift's peculiar way of dealing with optional protocol requirements. Optional protocol properties have no setter. (I regard this as a bug in the language.) You'll have to work around it.

You can say (horrible):

switch view {
case let field as UITextField:
    field.enablesReturnKeyAutomatically = true
case let field as UITextView:
    field.enablesReturnKeyAutomatically = true
default: break

Another way (equally horrible):

let setter = #selector(setter:UITextInputTraits.enablesReturnKeyAutomatically)
if view.responds(to:setter) {
    view.perform(setter, with: 1 as NSNumber)