Objective C - 声明属性的可选字段

e.T*_*T55 3 objective-c

是否有任何解决办法可以在 Objective ci 中找不到任何将 Bool 和 float 类型设置为可选的?

 @property (nonatomic, assign) float percentageOfCases;
    @property (nonatomic, assign) float inspectionPercentageOfCases;
    @property (nonatomic, assign) NSString<Optional> *inspectionStatus;
@property (nonatomic, assign) BOOL sendNotification;
Run Code Online (Sandbox Code Playgroud)

rob*_*off 5

SwiftOptional对应于 Objective-C 中的可空性,而在 Objective-C 中,只有指针类型可以为空。因此,您必须将属性更改为指针类型,在本例中这意味着NSNumber *对于float属性以及NSNumber *或者CFBooleanRef对于BOOL属性。

但是,更改类型将使 Swift 将属性导入为 和NSNumberCFBoolean不是 asFloatBool。因此,您可能还想应用NS_REFINED_FOR_SWIFT到每个属性,并使用 Swift来定义类型和extension的属性。它看起来是这样的:FloatBool

// In your Objective-C header:

@interface MyObject : NSObject
@property (nonatomic, assign, nullable) NSNumber *percentageOfCases NS_REFINED_FOR_SWIFT;
@property (nonatomic, assign, nullable) NSNumber *inspectionPercentageOfCases NS_REFINED_FOR_SWIFT;
@property (nonatomic, assign, nullable) NSString *inspectionStatus;
@property (nonatomic, assign, nullable) CFBooleanRef sendNotification NS_REFINED_FOR_SWIFT;
@end
Run Code Online (Sandbox Code Playgroud)
extension MyObject {
    var percentageOfCases: Float? {
        get { __percentageOfCases?.floatValue }
        set { __percentageOfCases = newValue as NSNumber? }
    }

    var inspectionPercentageOfCases: Float? {
        get { __inspectionPercentageOfCases?.floatValue }
        set { __inspectionPercentageOfCases = newValue as NSNumber? }
    }

    var sendNotification: Bool? {
        get { (__sendNotification as NSNumber?)?.boolValue }
        set { __sendNotification = newValue as NSNumber? }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,Xcode 不会双下划线标识符(如__percentageOfCases)提供代码补全。