Using readLine()
and AnyGenerator
to construct a String
array of the std input lines
readLine()
will read from standard input line-by-line until EOF is hit, whereafter it returns nil
.
Returns Character
s read from standard input through the end of the
current line or until EOF is reached, or nil
if EOF has already been
reached.
This is quite neat, as it makes readLine()
a perfect candidate for generating a sequence using the AnyGenerator
initializer init(body:)
which recursively (as next()
) invokes body
, terminating in case body
equals nil
.
AnyGenerator
init(body: () -> Element?)
Create a GeneratorType
instance whose next
method invokes body
and returns the result.
With this, there's no need to actually supply the amount of lines we expect from standard input, and hence, we can catch all input from standard input e.g. into a String
array, where each element corresponds to an input line:
let allLines = AnyGenerator { readLine() }.map{ $0 }
// type: Array<String>
After which we can work with the String
array to apply whatever operations needed to solve a given task (/HackerRank task).
// example standard input
4 3
<tag1 value = "HelloWorld">
<tag2 name = "Name1">
</tag2>
</tag1>
tag1.tag2~name
tag1~name
tag1~value
/* resulting allLines array:
["4 3", "<tag1 value = \"HelloWorld\">",
"<tag2 name = \"Name1\">",
"</tag2>",
"</tag1>",
"tag1.tag2~name",
"tag1~name",
"tag1~value"] */