[swift-evolution] Make non-void functions @warn_unused_result by default

Dave Abrahams dabrahams at apple.com
Thu Dec 17 17:36:32 CST 2015


> On Dec 10, 2015, at 2:58 PM, Adrian Kashivskyy via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I think non-void functions should warn about their return value being unused by default, thus eliminating the need to attribute them with @warn_unused_result.
> 
> Motivation
> 
> It is a rare case for a result of a function to be unused – and most often it's caused by programmer having too little knowledge of the API. This, in my opinion, is a reasonable area of improvement for the compiler.
> 
> I also noticed that many of stdlib's functions are marked with this attribute, which supports my point of this being the default behavior.
> 
> Example code
> 
> The following should be default behavior:
> 
>> func square(x: Int) -> Int { return x * x }
>> square(2) // warning: result of call to 'square' unused
> 
> Currently, unless annotated by @warn_unused_result, the compiler will not trigger any warnings.
> 
> Supporting old behavior
> 
> If, sometimes, it is okay to not use the result, an opposite @suppress_unused_result attribute could be used instead.
> 
>> @suppress_unused_result func square(x: Int) -> Int { return x * x }
>> square(2) // no warning
> 
> Impact on existing code
> 
> The existing bare @warn_unused_result attributes will become redundant and can be easily removed by migrator. However, if an existing attribute uses message or mutable_variant argument, it may be left intact, since it provides non-obvious informational value.
> 
> Implementing the above proposal would definitely make the code clearer and intentional, without compromising any major use cases.
> 
> I would be happy to hear your thought on this.
>  
> 
> Regards,
> Adrian Kashivskyy
> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

strong +1 from me.  @warn_unused_result is almost always the right answer in the standard library, and the few cases where it isn’t are very easy to notice (when the call has side-effects and the return value is incidental).

-Dave



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151217/a79dc394/attachment.html>


More information about the swift-evolution mailing list