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?

SPQR3
  • 647
  • 7
  • 20

2 Answers2

6

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

LDNZh
  • 1,136
  • 8
  • 14
  • love the compactness of the ternary operator – Hamish Jan 19 '16 at 11:56
  • Thanks, I didn't know the ternary operator worked this way when the second parameter is omitted. More info: http://stackoverflow.com/questions/3319075/ternary-conditional-operator-behaviour-when-leaving-one-expression-empty – SPQR3 Jan 19 '16 at 12:11
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
Sahil
  • 9,096
  • 3
  • 25
  • 29