Constructing literals in Swift playgrounds without drag and drop

I first wrote about the literal system back when they were introduced in September. Playgrounds enable you to drag in and drop images, colors, and files.

Today, I thought I’d mention how these items are constructed, so you can build your own without actual draggage and droppage.

Colors, images, and file references are represented as:

[#Color(colorLiteralRed: red, green: green, blue: blue, alpha: alpha)#]
[#Image(imageLiteral: localResourceNameAsString)#]
[#FileReference(fileReferenceLiteral: localResourceNameAsString)#]

You can see this by selecting an in-playground item, copying it, and pasting to a text file.

Unfortunately, at this time, there doesn’t seem to be a way to use this to trick Xcode into building literal items for you:

The literal convertible types are defined in the Swift module but the actual implementation, I’d imagine is part of the playground dev tools base.

/// Conforming types can be initialized with color literals (e.g.
/// `[#Color(colorLiteralRed: 1, blue: 0, green: 0, alpha: 1)#]`).
public protocol _ColorLiteralConvertible {
    public init(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float)
} 

/// Conforming types can be initialized with strings (e.g.
/// `[#FileReference(fileReferenceLiteral: "resource.txt")#]`).
public protocol _FileReferenceLiteralConvertible {
    public init(fileReferenceLiteral: String)
}

/// Conforming types can be initialized with image literals (e.g.
/// `[#Image(imageLiteral: "hi.png")#]`).
public protocol _ImageLiteralConvertible {
   public init(imageLiteral: String)
}

And, no, I did not find any super secret other undocumented literals. Pity.

2 Comments

  • Great post! Time to update it for Xcode 8.1 😉

    • What big changes do I need to cover that I haven’t already in other posts?