Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 414
Brandon Bradley Avatar asked Oct 31 '15 05:10

Brandon Bradley


People also ask

How do I clear the terminal screen?

You can use Ctrl+L keyboard shortcut in Linux to clear the screen. It works in most terminal emulators.


2 Answers

You can use the following ANSI sequence:

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

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

like image 70
Rudolf Adamkovič Avatar answered Oct 11 '22 14:10

Rudolf Adamkovič


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")
like image 34
JAL Avatar answered Oct 11 '22 15:10

JAL