[Pitch] Swift Snippets

One thing I haven't seen brought up in this thread: Rust has a related feature they call doctest. I believe it in turn was inspired by a Python tool that provided similar functionality. This is the relevant documentation for Rust.

To me the fact that these examples are tested (by default, you can customize with attributes) in addition to being compiled is perhaps the biggest selling point and something I have really enjoyed about Rust documentation. So many pieces of Rust docs have a handful of 1-2 line examples per function that you as the reader can be super confident in accurately describing the behaviour of whatever is being documented.

I also agree with what others have brought up: Having these examples right in the doc comment next to the thing they are describing/testing is very valuable and lowers the barrier to using the feature immensely. The argument the proposal brings forth against this, that tooling would not provide a good editing experience, does not convince me at all: We could undoubtedly teach SourceKit to highlight and complete code in doctest/snippet comments just as it does for normal code.

Now that I'm thinking about it, the thing I like most about the Rust feature is probably that it simultaneously lowers the threshold for both testing and writing documentation (both areas that in my perception developers can be reluctant to start on). You don't need to set up a whole test suite or write paragraphs of prose; just chuck in a few example doctests and you have a great first step to test coverage and documentation for relatively small effort.

So, I would argue for testing these snippets by default, and for having the ability to include them right in doc comments next to what they're testing.

And one more related thought: It would be really cool if, either through a web service or though the WASM effort, we could edit and re-run snippets right on the documentation page, but that's a future direction at most :D

2 Likes