cph2117
cph2117

Reputation: 2681

Null string crashes Swift conditional

I have a String property as part of a custom object. When I try to access the String on the custom object (when it's Null), the program crashes.

I can tell that the string is of type NSNull by printing out the custom object.

Every time I try

if theString == nil if theString == NSNull() if theString.isEmpty

the program crashes with [NSNull length]: unrecognized selector sent to instance

What I don't understand is where it's trying to call length. I would imagine it only calls length on the isEmpty function, but it crashes on the other two conditionals as well.

I'm thinking it could be because the custom object is created in objective-c with an NSString, but this also crashes when I try to convert the String to an NSString, so I'm not sure how to go about it.

Thanks!

Upvotes: 1

Views: 1091

Answers (1)

cph2117
cph2117

Reputation: 2681

I don't like answering my own questions, but for what it's worth, if an Obj-C property is NSNull and you attempt to unwrap it in Swift, it will give you an error.

I fixed this by doing a check on my custom object (in Obj-C model), and if a property is NSNull then you set that property equal to nil like so:

if (theString == (id)[NSNull null]){
     theString = nil

}

Upvotes: 3

Related Questions