我有一个可以返回nil的方法。如果它没有返回nil,它应该替换一个局部变量:
NSString *errorMsg = error.localizedDescription;
if([self errorMsgFromErrorCode:error.code]) {
errorMsg = [self errorMsgFomErrorCode:error.code];
}
是否有更聪明更紧凑的方法来完成此操作而无需两次调用此辅助方法?
答案 0 :(得分:6)
errorMsg = [self errorMsgFromErrorCode:error.code] ?: error.localizedDescription;
答案 1 :(得分:0)
你可以使用条件运算符:
NSString *errormessage = [self errorMsgFromErrorCode:error.code] ? [self errorMsgFromErrorCode:error.code] : error.localizedDescription;
并且在swift中最短的形式是nil coalescing operator(??) 例如
var perhapsInt: Int?
let definiteInt = perhapsInt ?? 2
print(definiteInt) // prints 2
perhapsInt = 3
let anotherInt = perhapsInt ?? 4
print(anotherInt) // prints 3