Swift 2.0 : How to print

Rest in peace, println. print is the new Swift 2.0 hotness. To print on a single line, use the optional appendNewline: argument. Otherwise print defaults to adding a carriage return at the end of each line.

print("test ", appendNewline: false); print("this")

Remember the Printable and DebugPrintable protocols which were used to output user-consumable and developer-consumable strings? They’re now CustomStringConvertible and CustomDebugStringConvertibleYou create the same description and debugDescription string properties but declare the updated protocols.

Other than that, everything remains pretty much the same. The following example prints to stderr, adding a new line after the string argument.

public struct StderrOutputStream: OutputStreamType {
   public mutating func write(string: String) {
       fputs(string, stderr)}
}
public var errStream = StderrOutputStream()

debugPrint("Hello", &errStream) // prints with new line

p.s. If you want to test the stderr output, use a real app, not a playground. 2.0 playgrounds are pretty unstable and this will crash them.

5 Comments

  • I personally liked having both println and print; having to add appendNewLine:false to every previous println statement looks a bit inefficient to me, I hope the decision will be reversed (it wont, I know).

    • Thanks for the helpful post.

      This might be a recent change but the parameter is now “appendNewline:false” not “appendNewLine:false”.

      Cheers

      • thanks

  • An even more recent change: as of the way to suppress newlines is now: terminator: “”

    Attempting to use appendNewline: false yields error: /newline.swift:3:1: error: ‘print(_:appendNewline:)’ is unavailable: Please use ‘terminator: “”‘ instead of ‘appendNewline: false’: ‘print((…), terminator: “”)’