No setter method for assignment to property swift

2019-07-14 03:59发布

问题:

I am using below code in one of my swift classes:

    import UIKit

public class BRUFIMobile: NSObject {

    public var mobileNumber : NSString?
    public var provider : NSString?
    public var aliasName: NSString?
    public var aliasName_en : NSString?
    @objc public var isDefault: Bool

    public override init() {
        self.isDefault = false
        super.init()
    }

}

My project contains both objective-c and swift codes. The code works fine on xCode 7 but now by updating to xCode 8 I get below error:

No setter method 'setIsDefault:' for assignment to property

I use the attribute in my objective-c code like below:

   + (BRUFIMobile *) convertUFIMobileToBRUFIMobile:(UFIMobile *) ufimobile
{
    BRUFIMobile *brUFIMobile = [[BRUFIMobile alloc] init];
    brUFIMobile.mobileNumber = ufimobile.number;
    brUFIMobile.provider = ufimobile.provider;
    brUFIMobile.aliasName = ufimobile.aliasName;
    brUFIMobile.aliasName_en = ufimobile.aliasName_en;
    brUFIMobile.isDefault = [ufimobile.isDefault boolValue];

    return brUFIMobile;
}

is it now neccessary to define seetters manually?

回答1:

Swift 3 beta makes special treatment for properties with leading is. For the property isDefault, Swift generates isDefault as getter and setDefault: as setter (not setIsDefault:).

Use setDefault: in your Objective-C code, or make it a computed property and give @objc names manually.


(Addition) "make it a computed property" means something like this:

private var _default: Bool = false
public var isDefault: Bool {
    @objc(isDefault) get {
        return _default
    }
    @objc(setIsDefault:) set {
        self._default = newValue
    }
}

(Update) As far as I tested, this seems to work:

@objc(isDefault) public var isDefault: Bool

A little bit simpler than "making it a computed property". Please try.


(Update2)

Apple Staff has confirmed that "This is a known issue that will be fixed in a future beta:" https://github.com/apple/swift/pull/3254

This is not a Core Data case. But the fix will work for this issue as well. (It's a pity, as for now, Xcode 8 beta 2 does not include this fix.)


(Update3) It is said in Xcode 8 beta 3 Release Notes that this feature is removed and I have confirmed that, with no @objc attribute, Objective-C setter setIsDefault: is available for Bool property isDefault.