简体   繁体   中英

Assign optional return value to variable

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?

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

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 eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM