Tutorials  /  Python

Swift readLine() and Swift print()

Ccentron Redaktion · January 2024 ·4 min read ·Python, Tutorial

Introduction

In this tutorial, we’ll be discussing how to read the standard input in Swift from the user and the different ways to print the output onto the screen. Swift print() is the standard function to display an output onto the screen. Let’s get started by creating a new command line application project in XCode.

VM

Matching infrastructure at centron

Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €3.12 per month, billed by the hour. Rent a cloud server →

Swift Input

In Swift, the standard input is not possible in Playgrounds. Neither in iOS Application for obvious reasons. Command Line Application is the possible way to read inputs from the user. readLine() is used to read the input from the user. It has two forms:

  • readLine() : The default way.
  • readLine(strippingNewLine: Bool) : This is default set to true. Swift always assumes that the newline is not a part of the input

readLine() function always returns an Optional String by default. Add the following line in your main.swift file.

Python
let str = readLine() //assume you enter your Name
print(str) //prints Optional(name)

To unwrap the optional we can use the following code:

Python
if let str = readLine(){
    print(str)
}

Reading an Int or a Float

To read the input as an Int or a Float, we need to convert the returned String from the input into one of these.

Python
if let input = readLine()
{
    if let int = Int(input)
    {
        print("Entered input is \(int) of the type:\(type(of: int))")
    }
    else{
        print("Entered input is \(input) of the type:\(type(of: input))")
    }
}

For Float, replace Int initialiser with the Float.

Reading Multiple Inputs

The following code reads multiple inputs and also checks if any of the input is repeated.

Python
while let input = readLine() {
    guard input != "quit" else {
        break
    }
    
    if !inputArray.contains(input) {
        inputArray.append(input)
        print("You entered: \(input)")
    } else {
        print("Negative. \"\(input)\" already exits")
    }
    
    print()
    print("Enter a word:")
}

The guard let statement is used to exit the loop when a particular string is entered print() as usual prints the output onto the screen. The current input is checked in the array, if it doesn’t exist it gets added. A sample result of the above code when run on the command line in Xcode is given below.

Reading Input Separated by Spaces

The following code reads the inputs in the form of an array separated by spaces.

Python
let array = readLine()?
    .split {$0 == " "}
    .map (String.init)

if let stringArray = array {
    print(stringArray)
}

split function acts as a delimiter for spaces. It divides the input by spaces and maps each of them as a String. Finally they’re joined in the form of an array.

Reading a 2D Array

The following code reads a 2D Array

Python
var arr = [[Int]]()
for _ in 0...4 {
    var aux = [Int]()

    readLine()?.split(separator: " ").map({
        if let x = Int($0) {
        aux.append(x)
        }
        else{
            print("Invalid")
        }
    })
    arr.append(aux)
}

print(arr)

In the above code we can create 4 sub arrays inside an array. If at any stage we press enter without entering anything in the row, it’ll be treated as a empty subarray.

Swift print()

We’ve often used print() statement in our standard outputs. The print function actually looks like this: print(_:separator:terminator:) print() statement is followed by a default new line terminator by default

Python
print(1...5) //// Prints "1...5"
print(1.0, 2.0, 3.0, 4.0, 5.0) //1.0 2.0 3.0 4.0 5.0
print("1","2","3", separator: ":") //1:2:3

for n in 1...5 { print(n, terminator: "|") } //prints : 1|2|3|4|5|

print("1","2","3", separator: ":") //1:2:3

for n in 1...5 { print(n, terminator: "|") } //prints : 1|2|3|4|5|

  • terminator adds at the end of each print statement.
  • separator adds between the output values.

Concatenating string with values

We use \(value_goes_here) to add values inside a string.

Python
var value = 10
print("Value is \(value)") // Value is 10

This brings an end to this tutorial on Swift Standard Input and Output.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren