Suppose you have a string
that contains many encoded values in it, like numbers and strings. This could be a from a file that saves user settings.
With Scanner, part of Foundation, we can parse these values in the order they are stored. Optional
values are returned. Many helpful methods, like scanUpToString
, can be used.
This program creates 2 Scanners and uses them in different ways. It imports Foundation, which is necessary to access the Scanner without a compile-time error.
string
parameter to it. The input string
literal includes some encoded values like the number 123456.scanUpToString
on the Scanner instance. We specify a space, so the string
returned includes all values until a space occurs.scanInt
. This returns an Optional
int
, so we must test it to ensure it has a value.scanDecimal
call works the same way as scanInt
. This will handle the value 12.3, which has a fractional value.isAtEnd
.import Foundation // Step 1: create a Scanner with the specified input string. let input = "bird 123456 12.3" let scanner = Scanner(string: input) // Step 2: scan a string from the input string up to a space. let word = scanner.scanUpToString(" ") print(word ?? "None") // Step 3: scan an int after the first scanned word. let intNext = scanner.scanInt() print(intNext ?? "None") // Step 4: scan a decimal afterwards. let decimalNext = scanner.scanDecimal() print(decimalNext ?? "None") // Step 5: create a Scanner and evaluate it in a loop with isAtEnd. let scanner2 = Scanner(string: "123 124 125") var sum = 0; while !scanner2.isAtEnd { // Scan an int, print a message and sum up the int. let intScanned = scanner2.scanInt() ?? 0 print("Summing \(intScanned)") sum += intScanned } print("Sum: \(sum)")bird 123456 12.3 Summing 123 Summing 124 Summing 125 Sum: 372
It is possible to parse a string
by first splitting it, but a Scanner can eliminate this step. Scanners maintain their position internally, which makes them more usable.