Brandon Bradley
Brandon Bradley

Reputation: 3378

How to clear the Terminal screen in Swift?

I am writing a BASIC Interpreter for the Command Line in Swift 2, and I cannot find a way to implement the simple command, CLS (clear all text from the Terminal.) Should I simply print spaces in a loop, or is there a function I'm not aware of that would clear the Terminal screen?

Upvotes: 7

Views: 13651

Answers (6)

TheMexican
TheMexican

Reputation: 1

if you are inside the REPL just type

:shell clear

Upvotes: -1

Rudolf Adamkovič
Rudolf Adamkovič

Reputation: 31486

You can use the following ANSI sequence:

print("\u{001B}[2J")

... where \u{001B} is ESCAPE and [2J is clear screen.

Upvotes: 15

Arc676
Arc676

Reputation: 4465

Use the built-in clear command either with system

system("clear")

or popen (ask Google)

Alternatively, simulate the pressing of Ctrl+L using AppleScript via the command line:

osascript -e 'tell app "terminal" to tell app "system events" to keystroke "l" using {control down}'

EDIT: system is no longer available in newer verions of Swift. See Rudolf Adamkovič's answer.

Upvotes: 0

Chris
Chris

Reputation: 5617

This works for me in Swift 3.1

var clearScreen = Process()
clearScreen.launchPath = "/usr/bin/clear"
clearScreen.arguments = []
clearScreen.launch()
clearScreen.waitUntilExit()

You can create a function with a callback like this

func clearScreen(completion:@escaping (Bool) -> () ) {
        let clearScreen = Process()
        clearScreen.launchPath = "/usr/bin/clear"
        clearScreen.arguments = []
        clearScreen.terminationHandler = { task in completion(true) }
        clearScreen.launch()
        clearScreen.waitUntilExit()
}

Upvotes: 0

Alessandro Mascolo
Alessandro Mascolo

Reputation: 133

This code makes a synchronous call to the built-in clear command. This won't cause problem with readLine() since it prints the escape sequence returned by clear using Swift's print() function

var cls = Process()
var out = Pipe()
cls.launchPath = "/usr/bin/clear"
cls.standardOutput = out
cls.launch()
cls.waitUntilExit()
        print (String(data: out.fileHandleForReading.readDataToEndOfFile(), encoding: String.Encoding.utf8) ?? "")

Upvotes: 1

JAL
JAL

Reputation: 42449

This answer applies to Swift 2.1 or earlier only

To elaborate on Arc676's answer:

The system command is imported into Swift via the Darwin module on Mac platforms (with other C APIs). On Linux, Glibc replaces Darwin for bridging low-level C APIs to Swift.

import Glibc

// ...

system("clear")

Or, if the system call is ambiguous, explicitly call Glibc's system (or Darwin on Mac platforms):

import Glibc

// ...

Glibc.system("clear")

Upvotes: 2

Related Questions