Difference between revisions of "Code Snippet: User Input-Single Line"

From Coder Merlin
Line 2: Line 2:


== Reading a single line of text from the console ==
== Reading a single line of text from the console ==
<syntaxhighlight lang="swift">
<syntaxhighlight lang="swift">
// Read a single line of input from the console
// Read a single line of input from the console
Line 17: Line 16:
     print("You typed: \(text)")
     print("You typed: \(text)")
}
}
</syntaxhighlight>
== Reading multiple lines of text from the console ==
<syntaxhighlight lang="swift">
// Read multiple lines from the console until end-of-file
var line : String?
repeat {
    line = readLine()                // Read a single line of input from the console
    if let text = line {            // Let's check if it's not nil, if so, it's really a string
        print("You typed: \(text)")  // Print the string
    }
} while line != nil                  // Continue until end-of-file
</syntaxhighlight>
</syntaxhighlight>

Revision as of 23:40, 3 December 2018

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Note: Input read from the console is terminated with a ^D (Control-D) which indicates the end-of-file.

Reading a single line of text from the console[edit]

// Read a single line of input from the console
let line = readLine()            // This will return an optional string
if line != nil {                 // Let's check if it's not nil, if so, it's really a string
    let text = line!             // Unwrap the string
    print("You typed: \(text)")  // Print the string
}
// Read a single line of input from the console (syntactic sugar)
if let text = readLine() {
    print("You typed: \(text)")
}

Reading multiple lines of text from the console[edit]

// Read multiple lines from the console until end-of-file
var line : String?
repeat {
    line = readLine()                // Read a single line of input from the console
    if let text = line {             // Let's check if it's not nil, if so, it's really a string
        print("You typed: \(text)")  // Print the string
    }
} while line != nil                  // Continue until end-of-file