0

There is an issue I have in swift with the object type conformed to @objc protocol with the property that is defined as @optional var.

Swift 5.3.2 assumes that optional property is immutable.

import Foundation

@objc protocol Bar {
    @objc var mutableVar: Bool { get set }
    @objc optional var mutableVar2: Bool { get set }
}

func foo(_ object: AnyObject & Bar) {
    var object = object
    object.mutableVar = false // compiles fine
    object.mutableVar2 = false // error: Can not assign to property: 'object' is immutable
}
Eugene Dudnyk
  • 5,553
  • 1
  • 23
  • 48
  • Read [this](https://www.bignerdranch.com/blog/protocol-oriented-problems-and-the-immutable-self-error/) - because `view` is a reference type, `self` - the reference to the view - is immutable. The object that `self` refers to is mutable, but that isn't how the protocol works. – Paulw11 Jan 15 '21 at 12:01
  • @Paulw11: I am not sure if that duplicate is chosen correctly. Here UITextInputTraits *is* an Objective-C protocol and applies only to class types. I also verified in a small test that the problem occurs only with protocol methods marked as `optional`. – Martin R Jan 15 '21 at 12:12
  • I edited the question - it is related to optional property only. – Eugene Dudnyk Jan 15 '21 at 12:13
  • I have changed the duplicate target to https://stackoverflow.com/q/26083377. That thread contains an explanation and a workaround. – Martin R Jan 15 '21 at 12:15
  • @MartinR Thanks. Yeah, I saw it, it's an old question for swift version 2 or 3, and the compiler error message is now different. I thought maybe there is a way to optionally assign the value. – Eugene Dudnyk Jan 15 '21 at 12:20

0 Answers0