0

I have a method which can return nil. If it doesn't return nil, it should replace a local variable:

NSString *errorMsg = error.localizedDescription;
if([self errorMsgFromErrorCode:error.code]) {
    errorMsg = [self errorMsgFomErrorCode:error.code];
}

Is there a smarter more compact way to do this without having to call this helper method twice?

2 Answers 2

6

errorMsg = [self errorMsgFromErrorCode:error.code] ?: error.localizedDescription;

Sign up to request clarification or add additional context in comments.

2 Comments

love the compactness of the ternary operator
Thanks, I didn't know the ternary operator worked this way when the second parameter is omitted. More info: stackoverflow.com/questions/3319075/…
0

you can use conditional operator:

NSString *errormessage = [self errorMsgFromErrorCode:error.code] ? [self errorMsgFromErrorCode:error.code] : error.localizedDescription;

and in swift the shortest form is nil coalescing operator (??) for e.g

var perhapsInt: Int?
let definiteInt = perhapsInt ?? 2
print(definiteInt) // prints 2 
perhapsInt = 3
let anotherInt = perhapsInt ?? 4
print(anotherInt) // prints 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.