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
}
5
  • Read this - 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. Commented Jan 15, 2021 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. Commented Jan 15, 2021 at 12:12
  • I edited the question - it is related to optional property only. Commented Jan 15, 2021 at 12:13
  • I have changed the duplicate target to stackoverflow.com/q/26083377. That thread contains an explanation and a workaround. Commented Jan 15, 2021 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. Commented Jan 15, 2021 at 12:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.