How to Print: the Beta 6 edition #swiftlang

Forget everything new about printing. RIP appendNewline. RIP last-position output stream. Print is new, redesigned, and totally facelifted in Beta 6.

Here’s what those public faces look like (and check out those hot non-terminal variadics):

public func print(items: Any..., separator: String = default, terminator: String = default) 

public func print<Target : OutputStreamType>(items: Any..., separator: String = default, terminator: String = default, inout toStream output: Target)

In its most basic form, you still print things:


and Swift will use a variety of protocols (Streamable, CustomStringConvertible, CustomDebugStringConvertible, those do not appear to have changed) to write a textual representation to stdout.

In Swift 2.0 beta 6 and above, you can print several things at once:

print(thing, anotherThing, yetAnotherThing)

Two special parameters (separator and terminator) control what happens between items and at the end of lines. An output parameter toStream controls where text is sent.

So if you’re writing an IRC client, you might send both \r and \n.

print(myText, terminator:"\r\n", toStream:&myIRCStream)

Or you might create a comma delimited list of integers:

print(1, 5, 2, 3, 5, 6, separator:", ")

You skip newlines by overriding the default terminator:

print("on one line", terminator:""); print("on the same line")

As with earlier Swift 2.0’s, strings conform to OutputStreamType, so you can print to strings:

var string =""; print("hello", toStream:&string)

Probably the most useful thing about print is that its new variadic arguments are all Any, so you can create a heterogeneous list of strings and items of interest, e.g.

print("My number is ", myNumber, " And this one is ", otherNumber)

without having to use in-line escaping (although it remains there if you really want it). This way, if your function calls use quote marks you don’t have to go through the compute then print work-arounds you had to in earlier betas.

Here’s a quick overview of what this all looks like:

Screen Shot 2015-08-24 at 5.53.29 PM


  • Thanks for writing this up so quickly after the release of beta 6! I like the pattern of putting strings and variables together in one call.

  • As long as default separator parameter is just simple whitespace ” ” the latest example should look like: print(“My number is”, myNumber, “And this one is”, otherNumber) – no need to add spaces at the beginning and at the end of these strings 🙂

    Anyway, thanks for this post! Good work 🙂

  • Awesome, you’re right, Tomasz. Even better!

  • […] 本文由CocoaChina译者 浅夏@旧时光 翻译自Erica Sadun原文:How to Print: the Beta 6 edition #swiftlang […]