Swift is now open source. For the latest news, visit the Swift open source blog

Literals in Playgrounds

New in Xcode 7.1 is the ability to embed file, image, and color literals into your playground’s code. Literals are the actual values of your data represented in their native format, directly within the Xcode editor. For instance, there’s no need to type “myImage.jpg” in the editor – just drag your image from the Finder and the actual image will appear in-line with your code. Instead of showing RGB values to indicate color, the playground will render a color swatch. Literals in playgrounds behave similarly to code you would otherwise hand-author in regular Swift code, but are rendered in a much more useful manner.

In addition to looking cool, literals can also make editing resources much faster. You can use the color picker to quickly choose a different color from the palette. Drag-and-drop files from the Finder into your playground code to start using them immediately. You can even add a literal at your current cursor position by selecting Editor > Insert File, Image, or Color Literal. Double-clicking a literal allows you to easily choose another value.

Resources are copied into your playground’s resources directory if needed, so everything your playground requires is included within the document. Because literals are part of your code, you can also copy, paste, move, and delete them exactly how you would any source code.

Literals in Swift Code

Literals translate into platform-specific types, the defaults of which are listed below:

Object LiteralOS XiOS and tvOS
ColorNSColorUIColor
FileNSURLNSURL
ImageNSImageUIImage

To get the full in-line presentation experience of literals, you must be in a playground. However, if you copy and paste code that uses literals into your main Swift source code, the pasted code will work as expected and Xcode will simply render the literals as plain text.

To get you started with literals we’ve included a very short playground in this blog post. Download the latest Xcode 7.1 beta to give this playground a try.

Additional Documentation

Documentation accompanying Xcode 7.1 beta 3 includes an updated playgrounds help document with new information on the many powerful features in playgrounds, including new content on literals. Here are direct links to the relevant sub-pages: Adding Image Literals, Adding Color Literals, and Adding File Literals.

Below is a screenshot demonstrating how literals appear within Xcode 7.1:

Literals in a Playground

All Blog Posts