Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring return value of function declared with "warn_unused_result" attribute

We start having this warning on all the becomeFirstResponder function call in our Objective-C code.

Ignoring return value of function declared with "warn_unused_result" attribute

[self.phoneNumberField becomeFirstResponder]; // warning here!!!

What's the best way to suppress this warning here?


Edit: I also tried this,

BOOL ignore = [self.emailField becomeFirstResponder]; 

But with that, Xcode has warning about the variable ignore is not used :(


I also tried this,

BOOL ignore = [self.phoneNumberField becomeFirstResponder];
if (ignore) {

}

The warnings is gone in this case. But I don't think I can even past my own code review. It is too ugly!

like image 671
Yuchen Avatar asked Apr 05 '17 17:04

Yuchen


2 Answers

It should work to cast the expression to a void expression.

(void)[self.emailField becomeFirstResponder]; 

(Even I cannot reproduce the warning. However, this might depend on the warning flags.)

To your edit:

BOOL ignore = [self.emailField becomeFirstResponder]; 

Likely

BOOL ignore = [self.emailField becomeFirstResponder]; 
ignore = ignore;
// or
(void)ignore;

should remove the warning. (It does with my flags.) However, this an ugly hack, too.

BTW: There is a reason for the attribute. Maybe you should recheck, whether it is a good idea, not to test for the return value.

like image 121
Amin Negm-Awad Avatar answered Oct 09 '22 05:10

Amin Negm-Awad


You could get this warning if you have a Swift function that you call from Objective-C code. You can silence it by adding @discardableResult before the function in Swift, like this:

@objc @discardableResult func yourFanzyFuncInSwift(argument: String) -> Bool { ... }

Seems like warn_unused_result is the default setting in Swift, meaning that you shouldn't write code that ignores return values.

like image 21
turingtested Avatar answered Oct 09 '22 04:10

turingtested