# Swift Snippets

**URL:** <https://forums.swift.org/t/swift-snippets/51947>\
**Category:** Pitches\
**Created:** [September 10, 2021, 3:44pm UTC](https://forums.swift.org/t/swift-snippets/51947 "2021-09-10T15:44:24Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![bitjammer](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bitjammer/32/18612_2.png) [@bitjammer](https://forums.swift.org/u/bitjammer)\
**Post date:** [September 10, 2021, 3:44pm UTC](https://forums.swift.org/t/swift-snippets/51947/1 "2021-09-10T15:44:24Z")

</div>

# Swift Snippets

Hello everyone,

Continuing the discussion started in [Command Line UX Enhancements for `swift`](https://forums.swift.org/t/command-line-ux-enhancements-for-swift/50670/4), I'd like to introduce some experimental work for a new Swift Package Manager feature for _snippets_.

We all know that learning by example is great, especially for code. I wanted to create the smallest, simplest method of providing example code for Swift packages, and I've just landed some [work in progress in the Swift Package Manager](https://github.com/apple/swift-package-manager/commit/a0ffd92a2c80f2c4677d696e248f4cfbec9d6540).

First and foremost a teaching tool, snippets are a small, focused, single file of example code that teaches a specific concept or API. Each snippet is a piece of the puzzle for documenting and showing best practices for your packages. They can also stand alone as a series of exercises, examples, or code recipes.

Each snippet file implies an executable target in the package that builds alongside the other targets in a package, ensuring that your examples always build. They can automatically import any library that a package defines, along with those normally available in an SDK, or whatever is the equivalent for your platform.

You can think of this work on snippets as both a new file format for sample code, and an initial implementation of a UX for interacting with those snippets (via SwiftPM.) It is easy to imagine other editors, IDEs, education apps, or documentation tools interacting with snippet files to teach in new and exciting ways.

## Writing and organizing snippets in a package

Here's an example snippet file:

```swift
//! Does a foo.

import MyModule

func foo() {}

// MARK: Hide

print(...)

// MARK: Show

func bar() {
    foo()
}

```

The `//!` comment is presented as a brief explanation for the snippet. This comment does not show inline in the source but at the top or in a listing for searching and browsing. Feel free to use regular comments if you need to explain the flow of a snippet.

The `MARK: Hide` comment tells the snippet system that the line and subsequent lines should be hidden but kept for building and running. A `MARK: Show` line will toggle that and lines will start showing again. This is how you separate _presentation code_ from _demo code_, or _glue code_ if you like.

The above snippet would present via SwiftPM like so:

**Does a foo.**

```swift
import MyModule

func foo() {}

func bar() {
    foo()
}

```

To start adding snippets to a package, create a `Snippets` directory alongside the familiar `Sources` and `Tests` directory and start dropping `.swift` files into there–no configuration or manifest changes necessary.

```swift
📁 MyPackage
  📄 Package.swift
  📁 Sources/
  📁 Tests/
  📁 Snippets/
    📄 A.swift
    📄 B.swift
    📄 C.swift
    ...

```

As you can see, the simple case (above) is incredibly simple to get started. As your body of snippets grows, you can create subdirectories to serve as groups, and even add an `Explanation.md` file that provides an abstract for the group.

```swift
📁 MyPackage
  📄 Package.swift
  📁 Sources/
  📁 Tests/
  📁 Snippets/
    📁 Fizzing
      📄 Explanation.md
      📄 Fizz.swift
      ...
    📁 Buzzing
      📄 Explanation.md
      📄 Buzz.swift
      ...

```

## Browsing a package's snippets at the command line

Included in the initial code contribution is an interactive command line experience that presents snippets in menus, or _cards,_ along with short explanations. Here's what it looks like.

First, below is the _top card_. This shows either the snippets you have put into the `Snippets` directory or _snippet groups_, if you have opted to create those.

 ![Screen Shot 2021-09-09 at 10.39.34 AM](https://global.discourse-cdn.com/swift/original/3X/6/b/6b6cba2f5766eb1f6c2770d5637f621871e21154.jpeg)

Here below is the _snippet group card_. Grouping your snippets is optional, but it can help you organize your snippets by task or concept.

 ![Screen Shot 2021-09-09 at 10.39.41 AM](https://global.discourse-cdn.com/swift/original/3X/9/f/9f42480bfffbca55567dda04da6f331b521e7771.png)

Finally below is the card for a snippet. You can see the abstract, code, and an option to run the snippet.

 ![Screen Shot 2021-09-09 at 10.39.50 AM](https://global.discourse-cdn.com/swift/original/3X/2/2/22b257e413169bf1c7226694806caf77661012e6.png)

## Try it out!

Snippets are available for testing in the [Trunk Development snapshots](https://swift.org/download/). To try out the interactive experience at the command line, you first need some snippets. I've created a [dummy project](https://github.com/bitjammer/SnippetTest) for you to see the folder structure, which you can clone and try the command below or start adding them to your own packages.

Once you've got some snippets in your `Snippets` directory, set an environment variable `SWIFTPM_ENABLE_SNIPPETS` to enable the feature and use the new `swift-package` subcommand called `learn`.

```bash
export SWIFTPM_ENABLE_SNIPPETS=1 

swift package learn

```

## Questions?

Here are some answers to potential questions you might have about snippets:

> Why single files?

Example code projects are still useful vehicles for explaining complex applications that may pull in many concepts at the same time. However, they can grow to be quite large and difficult to maintain. They also present navigation challenges for beginners and experienced developers alike. SwiftPM already has executable targets in which many source files can take part. Snippets are a short path to creating digestable, searchable chunks of code.

> Are snippets just tests?

No, snippets aren't tests. Again, snippets are a teaching tool, and I wanted to provide a tool that lets package authors focus on teaching users how to use their package and not mix in complex concerns about setup, tear-down, and glue code that is not typical of real world use.

## Future Development

In the future, here are some aspects I would like to explore with snippets:

- Add syntax highlighting to code snippets at the command line. This is something that I have already started working on but will require a SwiftSyntax dependency.

- Presentation order of snippets and groups

- Export of snippet data for integration into DocC, The Swift Programming Language book, [swift.org](http://swift.org), and more

- Search for text and titles at the command line

- Turning snippets into high-level templates

- Creating a style guide for teaching with snippets

- Optional or uncommon features for Package.swift, such as excludes

I hope I've whetted your appetite and I'm curious to hear what you think about this approach.

Thanks! ▫

---

<div class="post-metadata">

**Author:** ![kiel](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kiel/32/1392_2.png) [@kiel](https://forums.swift.org/u/kiel)\
**Post date:** [September 11, 2021, 2:48am UTC](https://forums.swift.org/t/swift-snippets/51947/2 "2021-09-11T02:48:05Z")

</div>

Would resources be something snippets should have access to? How does a Snippet process them etc? e.g.: teaching image manipulation APIs?

---

<div class="post-metadata">

**Author:** ![bitjammer](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bitjammer/32/18612_2.png) [@bitjammer](https://forums.swift.org/u/bitjammer)\
**Post date:** [September 11, 2021, 3:51am UTC](https://forums.swift.org/t/swift-snippets/51947/3 "2021-09-11T03:51:10Z")

</div>

Yes I think snippets should have access to resources already although not with any formal or explicit mechanism with the hopes of keeping it simple and as low resistance as possible. Right now, that means that related snippet resources should exist under the `Snippets` subdirectory, ideally next to the related snippet, and found by relative file path.

---

<div class="post-metadata">

**Author:** ![masters3d](https://avatars.discourse-cdn.com/v4/letter/m/c4cdca/32.png) [@masters3d](https://forums.swift.org/u/masters3d)\
**Post date:** [September 11, 2021, 2:17pm UTC](https://forums.swift.org/t/swift-snippets/51947/4 "2021-09-11T14:17:31Z")

</div>

1. does these snippets get vended as part package under Swift package registries?

2. could the Swift package snippet feature support Swift playgrounds files?

3. I really like this. I wonder if it could be all be in a mark down files with Swift code blocks that the package manager parses to vend the snippet, and docc artifacts. Something similar to [GitHub - fastai/nbdev: Create delightful software with Jupyter Notebooks](https://github.com/fastai/nbdev)

---

<div class="post-metadata">

**Author:** ![davdroman](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/davdroman/32/46501_2.png) [@davdroman](https://forums.swift.org/u/davdroman)\
**Post date:** [September 11, 2021, 2:18pm UTC](https://forums.swift.org/t/swift-snippets/51947/5 "2021-09-11T14:18:50Z")

</div>

This might be naive of me to ask but... how does this proposal add value differently from Xcode Playgrounds?

---

<div class="post-metadata">

**Author:** ![Morten\_Bek\_Ditlevsen](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/morten_bek_ditlevsen/32/28133_2.png) [@Morten\_Bek\_Ditlevsen](https://forums.swift.org/u/Morten_Bek_Ditlevsen)\
**Post date:** [September 11, 2021, 2:42pm UTC](https://forums.swift.org/t/swift-snippets/51947/6 "2021-09-11T14:42:53Z")

</div>

It could add value for non-Apple platforms.

---

<div class="post-metadata">

**Author:** ![xAlien95](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/xalien95/32/12558_2.png) [@xAlien95](https://forums.swift.org/u/xAlien95)\
**Post date:** [September 11, 2021, 3:05pm UTC](https://forums.swift.org/t/swift-snippets/51947/7 "2021-09-11T15:05:04Z")

</div>

The idea is interesting, thank you for exploring this field. That being said, DocC has been advertised as the best tool for generating package documentation and related learning experiences in general. Snippets can be added in a proper DocC Article or, depending on the circumstances, in a DocC Tutorial. I would expect a `swift package learn` command (if it existed) to serve the generated DocC HTML pages and open their main page in the user browser.  
DocC depends on Xcode, but if there's a chance to make it standalone and platform independent, I would happily prefer its integration in SPM over a command line interactive experience.

Edit: I didn't mean to reply to @davdroman, this post refers to the main topic. Sorry about that 😅

---

<div class="post-metadata">

**Author:** ![TimTr](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/timtr/32/14492_2.png) [@TimTr](https://forums.swift.org/u/TimTr)\
**Post date:** [September 11, 2021, 8:29pm UTC](https://forums.swift.org/t/swift-snippets/51947/8 "2021-09-11T20:29:45Z")

</div>

Snippets are intended to be complementary to DocC, where snippets could be imported (in the future) as samples presented within DocC documentation. This would allow CI to build and test the snippets to ensure the docs continue to present valid sample code, and identify when sample code needs to be updated. This is an early implementation, of course, with many cool ideas down stream starting from a very simple starting point.

---

<div class="post-metadata">

**Author:** ![TimTr](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/timtr/32/14492_2.png) [@TimTr](https://forums.swift.org/u/TimTr)\
**Post date:** [September 11, 2021, 8:32pm UTC](https://forums.swift.org/t/swift-snippets/51947/9 "2021-09-11T20:32:08Z")

</div>

Yes, a really important goal for Snippets is to work across all supported platforms. A big goal here is to start from the simplest possible case, and provide a super-easy method for package authors to share snippets that show off how to use their package. Would be great if everyone in the Swift ecosystem writing packages has a simple, standard way to show off their code, regardless of platform or use case.

---

<div class="post-metadata">

**Author:** ![davdroman](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/davdroman/32/46501_2.png) [@davdroman](https://forums.swift.org/u/davdroman)\
**Post date:** [September 12, 2021, 3:09am UTC](https://forums.swift.org/t/swift-snippets/51947/10 "2021-09-12T03:09:19Z")

</div>

> [@TimTr](#):
>
> This would allow CI to build and test the snippets to ensure the docs continue to present valid sample code, and identify when sample code needs to be updated.

This is brilliant.

Thank you for explaining 🙂

---

<div class="post-metadata">

**Author:** ![bitjammer](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bitjammer/32/18612_2.png) [@bitjammer](https://forums.swift.org/u/bitjammer)\
**Post date:** [September 12, 2021, 5:24am UTC](https://forums.swift.org/t/swift-snippets/51947/11 "2021-09-12T05:24:32Z")

</div>

Hi Cheyo!

As currently implemented, the snippets travel along with the package’s sources so, as long as those can be reached, the information about snippets could be packaged up in any number of ways depending on the environment. I see a package’s snippets existing both as a part of its documentation as well as some sort of “showcase” or accessible through some other direct way. Either of those things would make a lot of sense for a package registry.

That’s an interesting idea, thanks for the link! This is something I have thought about a lot in the past while working on DocC. I think my view right now is that you need both forms, Swift-inside-Markdown (like a DocC article) and Markdown-inside-Swift (like a doc comment), in order to easily tap the strengths of the respective formats. Since these are meant to be brief and not tutorial-like, I think the code will slightly outweigh the prose on these.

---

<div class="post-metadata">

**Author:** ![alexbbrown](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alexbbrown/32/14720_2.png) [@alexbbrown](https://forums.swift.org/u/alexbbrown)\
**Post date:** [September 15, 2021, 1:01am UTC](https://forums.swift.org/t/swift-snippets/51947/12 "2021-09-15T01:01:21Z")

</div>

The fact that snippets are executed (not just described) by the browser is somewhat underplayed in your description; you could promote that in the title perhaps.

These sound like CRAN vignettes.

Very cool

---

<div class="post-metadata">

**Author:** ![benrimmington](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/benrimmington/32/695_2.png) [@benrimmington](https://forums.swift.org/u/benrimmington)\
**Post date:** [September 15, 2021, 1:36pm UTC](https://forums.swift.org/t/swift-snippets/51947/13 "2021-09-15T13:36:40Z")

</div>

> [@bitjammer](#):
>
> The `//!` comment is presented as a brief explanation for the snippet. This comment does not show inline in the source but at the top or in a listing for searching and browsing. Feel free to use regular comments if you need to explain the flow of a snippet.

- Could this use the playground `//:` and `/*:` [comment markers](https://developer.apple.com/documentation/swift_playgrounds/writing_prose_for_a_playground_page)?
- And a subset of the same [markup functionality](https://developer.apple.com/library/archive/documentation/Xcode/Reference/xcode_markup_formatting_ref/MarkupFunctionality.html)?

> [@bitjammer](#):
>
> The `MARK: Hide` comment tells the snippet system that the line and subsequent lines should be hidden but kept for building and running. A `MARK: Show` line will toggle that and lines will start showing again. This is how you separate _presentation code_ from _demo code_, or _glue code_ if you like.

- And the same `//#-hidden-code` and `//#-end-hidden-code` [delimiters](https://developer.apple.com/documentation/swift_playgrounds/hiding_code_from_a_playground_page)?
- Basically, can we use the existing playground editors for snippets?

> [@bitjammer](#):
>
> As your body of snippets grows, you can create subdirectories to serve as groups, and even add an `Explanation.md` file that provides an abstract for the group.

- `README.md` would be better for browsing on GitHub, etc.
- Or should the explanation be in `//:` and `/*:` comments?

> [@bitjammer](#):
>
> Once you've got some snippets in your `Snippets` directory, set an environment variable `SWIFTPM_ENABLE_SNIPPETS` to enable the feature and use the new `swift-package` subcommand called `learn`.

- Should the subcommand be named after the feature and its directory?
- e.g. `swift package snippets` or `swift run --snippets`

---

<div class="post-metadata">

**Author:** ![bitjammer](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bitjammer/32/18612_2.png) [@bitjammer](https://forums.swift.org/u/bitjammer)\
**Post date:** [September 15, 2021, 7:08pm UTC](https://forums.swift.org/t/swift-snippets/51947/14 "2021-09-15T19:08:59Z")

</div>

> [@benrimmington](#):
>
> - Could this use the playground `//:` and `/*:` [comment markers](https://developer.apple.com/documentation/swift_playgrounds/writing_prose_for_a_playground_page)?
> - And a subset of the same [markup functionality](https://developer.apple.com/library/archive/documentation/Xcode/Reference/xcode_markup_formatting_ref/MarkupFunctionality.html)?

I think the style of comment marker isn't too important as long as it comes across as different. The `!` was just a placeholder. We will probably bikeshed things like this further in the future but don't want to get caught up in syntax just yet.

As for Markdown, I would expect it to eventually have the same capabilities as doc comments today, at least all of CommonMark, so that DocC and the Web can pick these up with parity.

It's possible that in the future these will interact with Playgrounds tooling and infrastructure but I don't want to design around that so all platforms can benefit equally at the inception. Not to worry, it is definitely in mind!

> [@benrimmington](#):
>
> - `README.md` would be better for browsing on GitHub, etc.
> - Or should the explanation be in `//:` and `/*:` comments?

Yes, I was thinking `README` could work although it feels very 'top-level' to me for some reason whereas these will be pretty frequent. This might be a good place to continue with the tradition, though.

The group explanations shouldn't be in doc comments because they may explain multiple files and no single `.swift` file should necessarily take ownership of that. It's generally best to write Markdown outside of doc comments to keep the tooling as flexible as possible.

> [@benrimmington](#):
>
> - Should the subcommand be named after the feature and its directory?
> - e.g. `swift package snippets` or `swift run --snippets`

Possibly, although this command will probably include other learning features for packages in the future. For example, typing `swift learn mutating` could certainly do something useful :). It's also possible to add a shortcut command to go straight to snippets as well. It should become more clear in the near future.

Thanks for your questions and comments!

---

<div class="post-metadata">

**Author:** ![Joseph\_Heck](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joseph_heck/32/22369_2.png) [@Joseph\_Heck](https://forums.swift.org/u/Joseph_Heck)\
**Post date:** [September 16, 2021, 8:08pm UTC](https://forums.swift.org/t/swift-snippets/51947/15 "2021-09-16T20:08:25Z")

</div>

For some reason, I didn't grok the benefits of this pitch when I first scanned through it - fixating a bit more on the CLI interactive component. While handy and interesting, in a re-read today I am far more excited about the potential to provide a way to have documentation examples inline with a project, and verify that they keep compiling, or show relevant errors or warnings when your code hits a deprecation use case.

I'm doubly thrilled at the include the mechanism (MARK in this case) that lets you separate setting up the example from showing the example. I've hit that myself repeatedly, and have a convention for my own use, but that doesn't cleanly parse for external systems (such as DocC), so I'm very excited to have a specific mechanism.

Finally - I know it's looking farther ahead than you're proposing with this pitch, but I'd love to also have a clear way to make sure each example snippet that may be presented (e.g. each card) has a clear identifier so that some future mechanism could explicitly curate the examples for presentation and even cross referencing (such as in externally rendered documentation), and not just relying on a default ordering from the internal systems.

---

<div class="post-metadata">

**Author:** ![bitjammer](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bitjammer/32/18612_2.png) [@bitjammer](https://forums.swift.org/u/bitjammer)\
**Post date:** [September 16, 2021, 8:30pm UTC](https://forums.swift.org/t/swift-snippets/51947/16 "2021-09-16T20:30:21Z")

</div>

> [@Joseph\_Heck](#):
>
> Finally - I know it's looking farther ahead than you're proposing with this pitch, but I'd love to also have a clear way to make sure each example snippet that may be presented (e.g. each card) has a clear identifier so that some future mechanism could explicitly curate the examples for presentation and even cross referencing (such as in externally rendered documentation), and not just relying on a default ordering from the internal systems.

Absolutely, this is actually near or at the top of the list for next steps. For sure we will want to be able to directly pick out specific snippets. It will likely be something like the relative path from the snippets directory including the filename (with or without extension), within the “namespace” of the package.

Also considering using an informal naming scheme to order snippets and groups using filenames without the need for explicit curation in an external source. But DocC will still need a way to curate or inline via links as needed. Stay tuned for that.

---

<div class="post-metadata">

**Author:** ![Kyle-Ye](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kyle-ye/32/19686_2.png) [@Kyle-Ye](https://forums.swift.org/u/Kyle-Ye)\
**Post date:** [August 16, 2022, 6:08am UTC](https://forums.swift.org/t/swift-snippets/51947/17 "2022-08-16T06:08:20Z")

</div>

Just trying to add Snippets support for swift-markdown [Add simple snippets support by Kyle-Ye · Pull Request #70 · apple/swift-markdown · GitHub](https://github.com/apple/swift-markdown/pull/70).

I was wondering when can we get some sort of support from the IDE not just the termial interface.

Maybe Xcode(waiting for Xcode team to support this GUI feature or maybe we can use the existing interface of XcodeProjectPlugin to support it) or VSCode Plugin could help on this (via [GitHub - swift-server/vscode-swift: Visual Studio Code Extension for Swift](https://github.com/swift-server/vscode-swift))

I've filed a feature request issue here [Add Swift Snippets GUI support in VSCode · Issue #391 · swift-server/vscode-swift · GitHub](https://github.com/swift-server/vscode-swift/issues/391)
