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

Kevin Ballard kevin at sb.org
Sat Dec 12 01:11:25 CST 2015

On Thu, Dec 10, 2015, at 04:41 PM, Dmitri Gribenko via swift-evolution wrote:
> We have discussed this internally in the past, and we found that non-
> mutating methods on structs and enums are usually @warn_unused_result,
> it is a quite strong heuristic.  With classes, especially Cocoa ones,
> it might not be the case.  It would be good if someone investigated
> how this change would affect a class-heavy library, e.g., Foundation.

I'm curious, what code did you look at to develop this heuristic? I've
noticed that the stdlib uses a lot of @warn_unused_result, but I don't
think I've ever actually seen anyone bother to use it in any of the third-
party Swift code that I've inspected.

My general feeling here is that, while most non-mutating functions that
return results probably aren't worth calling if you ignore the results,
that doesn't mean that @warn_unused_result is actually something that
should necessarily be expected to put on the declaration. Where it would
primarily be expected is on functions that look like they might be
mutating but aren't (think `sort()` vs `sortInPlace()`), or on functions
that return an object whose deinit triggers behavior that negates the
function call (e.g. some sort of `open()` that returns a File object). I
think the stdlib uses it a disproportionate amount because the stdlib is
used by everybody, and adding the attribute to stdlib declarations
therefore has a huge reach for little effort and in particular it may
help neophyte programmers.

I will accept that most calls to nonmutating methods on structs and
enums are probably good candidates for @warn_unused_result, I'm just
arguing that in most cases outside of the stdlib there's low reward for
adding it, and I worry that if we make it the default then we run the
risk of punishing users of side-effectful APIs where the API designer
never actually tried ignoring the results.

I do support Kametrixom's idea of a @pure attribute that implies both
@effects(readnone) and @warn_unused_result.

-Kevin Ballard
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151211/76615df7/attachment.html>

More information about the swift-evolution mailing list