Phan Van Linh Phan Van Linh - 1 month ago 6
iOS Question

Use nullable/nonnull for property that already have default value

I know the way to use

nonnull
and
nullable
is

nonnull: the value won’t be nil; bridges to a regular reference.
nullable: the value can be nil; bridges to an optional.


But in my case, the
titleColor
seems like both
nullable
and
nonnull
. It is
nullable
because we may not need to set value and it
nonnull
because it always has the default value. Do I understand correct and in my case, what should I choose nullable or nonnull?

// IN .h file
@property(nonatomic, strong) UIColor *titleColor;
// @property(nonatomic, strong, nullable) UIColor *titleColor;


// IN .m file
-(UIColor *)titleColor{
if(!_titleColor){
_titleColor = [UIColor greenColor];
}
return _titleColor;
}

Answer

Use nonnull if the setter won't accept nil and the getter won't ever return nil.

Use nullable if the setter will accept nil or if the getter will ever return nil.

Keep in mind that Objective-C won't really care what you actually do.

So if in Swift you would use an optional, then make it nullable, otherwise make it nonnull.