Reputation: 465
Is there any work around to set Bool and float types to Optional in objective c i couldn't find any?
@property (nonatomic, assign) float percentageOfCases;
@property (nonatomic, assign) float inspectionPercentageOfCases;
@property (nonatomic, assign) NSString<Optional> *inspectionStatus;
@property (nonatomic, assign) BOOL sendNotification;
Upvotes: 3
Views: 1704
Reputation: 385590
Swift's Optional
corresponds to nullability in Objective-C, and in Objective-C, only pointer types can be nullable. So you have to change your properties to be pointer types, which in this case means NSNumber *
for the float
properties and either NSNumber *
or CFBooleanRef
for the BOOL
property.
However, changing the types will make Swift import the properties as NSNumber
and CFBoolean
instead of as Float
and Bool
. So you probably also want to apply NS_REFINED_FOR_SWIFT
to each property, and a Swift extension
to define properties of type Float
and Bool
. Here's what it looks like:
// 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
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? }
}
}
Note that Xcode will not offer code completion for the double-underscored identifiers (like __percentageOfCases
).
Upvotes: 5