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

Adrian Kashivskyy adrian.kashivskyy at me.com
Thu Dec 10 16:58:00 CST 2015


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

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


More information about the swift-evolution mailing list