144

In swift 2.0, print() automatically adds a newline character. In swift 1.2, println() and print() used to be separate functions. So how do I print some text and not add a newline to it since swift no longer has a print function that does not append newlines.

Ankit Goel
  • 6,257
  • 4
  • 36
  • 48
  • possible duplicate of [How to print to console using swift playground?](http://stackoverflow.com/questions/24003092/how-to-print-to-console-using-swift-playground) – Dániel Nagy Jun 16 '15 at 10:56
  • 4
    @DánielNagy It is not a duplicate because swift 2.0 does not have a println function. I am not asking how to print to console because print function will do that. I am asking "How to print to console without the newline appended to input text" – Ankit Goel Jun 16 '15 at 10:59
  • 3
    This is explicitly documented in the Xcode 7 beta release notes: *"println and print have been merged together into a single print function with a default argument ..."* – Martin R Jun 16 '15 at 11:29

5 Answers5

268

Starting in Swift 2.0, the recommended method of printing without newline is:

print("Hello", terminator: "")
aheze
  • 24,434
  • 8
  • 68
  • 125
cheniel
  • 3,473
  • 1
  • 14
  • 15
  • Even though you only see the interface with the `seperator` parameter. You can simply ignore it because it has a default value `func print(items: Any..., separator: String = default, terminator: String = default)` – Binarian Sep 01 '15 at 11:34
  • 2
    Where in the Swift docs would someone find out what `default` is equal to? – 7stud Jan 06 '16 at 06:59
  • 1
    @7stud `default` is a placeholder for a default value. Ideally, the documentation should contain the actual value, not a placeholder. – Sulthan Feb 29 '16 at 09:10
  • 1
    Default values are : separator " "(single space) and terminator \n(new line) – selva Sep 19 '17 at 12:48
75

print function has changed completely since the late revision of Swift, now it looks much simpler and there are variant of method to print to standard console.

The method signature for print looks something like this,

public func print<Target>(_ items: Any..., separator: String = default, terminator: String = default, to output: inout Target) where Target : TextOutputStream

And here are some usecases,

print("Swift is awesome.")
print("Swift", "is", "awesome", separator:" ")
print("Swift", "is", "awesome", separator:" ", terminator:".")

Prints:

Swift is awesome.
Swift is awesome
Swift is awesome.

Concatenating

print("This is wild", terminator: " ")
print("world")

Prints:

This is wild world

So, using terminator, you should be careful that the contents are relevant to same line.

Printing Object with CustomStringConvertible

struct Address {
  let city: String
}

class Person {
  let name = "Jack"
  let addresses = [
    Address(city: "Helsinki"),
    Address(city: "Tampere")
  ]
}

extension Person: CustomStringConvertible {
  var description: String {
    let objectAddress = unsafeBitCast(self, to: Int.self)
    return String(format: "<name: \(name) %p>", objectAddress)
  }
}

let jack = Person()
print(jack)

Prints:

<name: Jack 0x608000041c20>

CustomDebugStringConvertible

extension Person: CustomDebugStringConvertible {
  var debugDescription: String {
    let objectAddress = unsafeBitCast(self, to: Int.self)

    let addressString = addresses.map { $0.city }.joined(separator: ",")
    return String(format: "<name: \(name), addresses: \(addressString) %p>",objectAddress)
  }
}

Now, with lldb, you can use po command and it will print object as this in lldb console,

<name: Jack, addresses: Helsinki,Tampere 0x60c000044860>

Logging to file using TextOutputStream

struct MyStreamer: TextOutputStream {

  lazy var fileHandle: FileHandle? = {
    let fileHandle = FileHandle(forWritingAtPath: self.logPath)
    return fileHandle
  }()

  var logPath: String = "My file path"

  mutating func write(_ string: String) {
    fileHandle?.seekToEndOfFile()
    fileHandle?.write(string.data(using:.utf8)!)
  }
}

Now, using print to stream,

print("First of all", to: &myStream )
print("Then after", to: &myStream)
print("And, finally", to: &myStream)

Prints to file:

First of all
Then after
And finally

CustomReflectable

extension Person: CustomReflectable {
  var customMirror: Mirror {
    return Mirror(self, children: ["name": name, "address1": addresses[0], "address2": addresses[1]])
  }
}

Now, in lldb debugger, if you use command po,

> po person

Result would be something like this,

▿ <name: Jack, addresses: Tampere Helsinki  0x7feb82f26e80>
  - name : "Jack"
  ▿ address1 : Address
    - city : "Helsinki"
  ▿ address2 : Address
    - city : "Tampere"
Sandeep
  • 20,908
  • 7
  • 66
  • 106
  • Also not working for me in Xcode 7beta4. Calling `print("foo", appendNewLine: false)` compiles but the output is `(foo), false` and a new line is appended anyway! – mluisbrown Aug 05 '15 at 21:47
  • @mluisbrown it's `appendNewline` (lower case `l`) – JeremyP Aug 17 '15 at 15:16
11

In Swift 2.0 you can do this:

Basic version

print("Hello World")
result "Hello World\n"

Using terminator

print("Hello World", terminator:"")
result "Hello World"

Using separator

print("Hello", "World", separator:" ")
result "Hello World\n"

Using separator and terminator

print("Hello", "World", separator:" ", terminator:"")
result "Hello World"

Using one variable

var helloworld = "Hello World"
print(helloworld)
result "Hello World\n"

Using two variables

var hello = "Hello"
var world = "World"
print (hello, world)
result "Hello World\n"
John Difool
  • 5,572
  • 5
  • 45
  • 80
Morten Gustafsson
  • 1,869
  • 2
  • 24
  • 34
4

If you want same line in loop:

for i in 1...4
{
    print("", i, separator: " ", terminator:"")
}
print()

Output: 1 2 3 4

PVCS
  • 3,831
  • 1
  • 16
  • 10
0
let description = String(describing: yourVariable)

The description variable here would hold exactly the same output you would get in console by using print() function.
So you can replace anything in the output.
For example I use this code to print JSON in single line:

print(description.replacingOccurrences(of: "\n", with: " "))
mykolaj
  • 974
  • 8
  • 17