In my Swift class, I exposed an variable to objective c by defining it as
@objc var textAlignment: NSTextAlignment? {
didSet {
if textAlignment != nil {
label.textAlignment = textAlignment!
}
}
}
And it is Wrong! because compiler complains that it is not a type that can be represented in Objective-C.
But the followings are right
var textAlignment: NSTextAlignment? {
didSet {
label.textAlignment = textAlignment!
}
}
Or
@objc var textAlignment: NSTextAlignment {
didSet {
label.textAlignment = textAlignment
}
}
So it looks like if I expose the method to objective-C, It can not be optional value. However if I use it internally, I can! Is it because it is a scalar value where in Objective-C we have no way to represent it as nil?
My intention was just want to make it not compulsory.
NSTextAlignment
is an enum, not an class - the textAlignment
variable can't be mapped as optional to objective c because that would require it to be a pointer to an object type.
Try:
@objc var textAlignment: NSTextAlignment {
...
}
Or, if you really need it to be optional, you could expose it to Objective C as an NSNumber
, wrapping the textAlignment.rawValue
or setting to nil when no value is needed.