Search code examples
iosobjective-cxcode7.3swift3

Swift - Check nil of an unwrapped optional variable


I am having a model class as follows, which is in a library written in Objective-C. I am consuming this class in my swift project. In swift it becomes property of type String!. Sometimes that property will be nil. So, I am testing the nil validation as follows:

Vendor.h

@interface Vendor: NSObject {

@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSString *middleName;
}

In my Swift project, I am checking the nil validation for the middleName property as below:

if anObject.middleNam != nil { // Here, It throws runtime error: fatal error: Unexpectedly found nil while unwrapping an Optional value
}

It throws me an following runtime error:

fatal error: unexpectedly found nil while unwrapping an Optional value

If the objective-C properties exposed in swift as String? then I would have used the following:

if let middleName = anObject.middleName {

}

How would I check for the unwrapped optional variable.

Thanks in advance.


Solution

  • If you want ObjectiveC property to be exposed in Swift as optional, mark it with _Nullable tag like

    @property (nonatomic, strong) NSString * _Nullable middleName;
    

    Now middleName name would be optional of type String? instead of String! and you could conditionally unwrap it.

    Read more about Nullability in ObjC