Alessio Crestani
Alessio Crestani

Reputation: 1612

EXC_BREAKPOINT on optional chaining

I'm new to Swift but I'm an experienced iOS dev on Objective-c. Currently, crashlytics have reported a EXC_BREAKPOINT crash to a single user, but it's systematic. I've tried with multiple devices and OSes version but I cannot reproduce It.

line is:

if(RealmManager.sharedInstance()?.loggedUser()?.agreementPhotoRead.boolValue ?? false || PreferencesManager.getTutorialDone(forEmail: RealmManager.sharedInstance()?.loggedUser()?.email)){
    }

What's wrong with optional chaining? Swift version is 4.2.

EDIT: geTutorialDone method is in objective-c. Here the code:

+ (BOOL)getTutorialDoneForEmail:(NSString *)email
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:[TUTORIAL_PREF stringByAppendingString:email]];
}

Upvotes: 0

Views: 246

Answers (1)

David Pasztor
David Pasztor

Reputation: 54716

The issue is that the stringByAppendingString method doesn't actually work in case its input argument NSString is nil as explained in the documentation of the method.

Raises an NSInvalidArgumentException if aString is nil.

You should do a nil check before calling the method in getTutorialDoneForEmail or even better, make getTutorialDoneForEmail accept only non-nil NSStrings.

+ (BOOL)getTutorialDoneForEmail:(nonnull NSString *)email {
    return [[NSUserDefaults standardUserDefaults] boolForKey:[TUTORIAL_PREF stringByAppendingString:email]];
}

Moreover, if agreementPhotoRead can be nil, you need to optional chain its call to boolValue, otherwise Swift will handle it as an implicitly unwrapped optional, which will result in a runtime error in case agreementPhotoRead was actually nil.

RealmManager.sharedInstance()?.loggedUser()?.agreementPhotoRead?.boolValue

Upvotes: 2

Related Questions