NSObject isEqual override in Swift 6

Hi, I'm having trouble while migration my code base to Swift 6.

the following code produce warning:
Main actor-isolated property 'field1Mode' can not be referenced from a nonisolated context; this is an error in the Swift 6 language mode


public enum FieldMode: Sendable {
    case normal
    case selected
    case editting
}

public class AttributeListLayoutAttributes: UICollectionViewLayoutAttributes {
    
    var field1Mode: FieldMode = .normal
    var field2Mode: FieldMode = .normal
    var field3Mode: FieldMode = .normal
    var updateSeed: Double = 0
    
    override public func copy(with zone: NSZone?) -> Any {
        guard let copiedAttributes = super.copy(with: zone) as? AttributeListLayoutAttributes else {
            return super.copy(with: zone)
        }
        copiedAttributes.field1Mode = field1Mode
        copiedAttributes.field2Mode = field2Mode
        copiedAttributes.field3Mode = field3Mode
        copiedAttributes.updateSeed = updateSeed
        return copiedAttributes
    }

    override public func isEqual(_ object: Any?) -> Bool {
        guard let attr = object as? AttributeListLayoutAttributes,
              field1Mode == attr.field1Mode, //Main actor-isolated property 'field1Mode' can not be referenced from a nonisolated context; this is an error in the Swift 6 language mode
              field2Mode == attr.field2Mode,
              field3Mode == attr.field3Mode,
              updateSeed == attr.updateSeed
        else {
            return false
        }
        return super.isEqual(object)
    }
}

How can I solve this problem?

Oh, I see, add nonisolated(unsafe) will mute the warning. Is there a better way to resolve this?

    nonisolated(unsafe) var field1Mode: FieldMode = .normal
    nonisolated(unsafe) var field2Mode: FieldMode = .normal
    nonisolated(unsafe) var field3Mode: FieldMode = .normal
    nonisolated(unsafe) var updateSeed: Double = 0
1 Like

You can use MainActor.assumeIsolated I guess.

1 Like