print without newline in swift

79,360

Solution 1

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

print("Hello", terminator: "")

Solution 2

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"

Solution 3

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"

Solution 4

If you want same line in loop:

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

Output: 1 2 3 4

Share:
79,360
Ankit Goel
Author by

Ankit Goel

Swift Developer. iOS. Vapor.

Updated on October 24, 2021

Comments

  • Ankit Goel
    Ankit Goel over 2 years

    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.

  • mluisbrown
    mluisbrown almost 9 years
    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!
  • JeremyP
    JeremyP over 8 years
    @mluisbrown it's appendNewline (lower case l)
  • Binarian
    Binarian over 8 years
    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)
  • 7stud
    7stud over 8 years
    Where in the Swift docs would someone find out what default is equal to?
  • Sulthan
    Sulthan about 8 years
    @7stud default is a placeholder for a default value. Ideally, the documentation should contain the actual value, not a placeholder.
  • selva
    selva over 6 years
    Default values are : separator " "(single space) and terminator \n(new line)
  • Jayram Kumar
    Jayram Kumar over 5 years
    By default the separator is a space " "