0

So, the input looks like this:

1 2  
3 4  
5 6  
7 8  

And I need to store each line as an array, like this:

[1, 2]
[3, 4]
[5, 6]
[7, 8]

I guess I can do this with .componentsSeparatedByString(" ") and then converting each element to an integer.

The problem is, I've tried using readLine(), but it only stores the first line, 1 2. I've thought about doing a while loop, but my input can contain more than 50 lines, and entering every single line would be pretty inconvenient.

Is there a way to store several lines as a string at once? It would also be good if I could replace the line breaks with ;, but I have no idea how, since it only stores the first line. Any help would be appreciated.

Thanks in advance!

  • Why readLine, are you making a CLI app and want to manage text file input? Or is it a normal app and you want to load a text file? – Eric Aya Jan 29 '16 at 18:19
  • @EricD. Yes, that is a CLI app and I need to work with the input, similar to which I provided in the very beginning. –  Jan 29 '16 at 18:24
  • If this is for OSX you can use NSFileHandle like here: http://stackoverflow.com/a/24021467/2227743 There's also different examples on this page. And NSFileHandle is not yet implemented in Swift.org's Foundation, so you can't use it for Linux. – Eric Aya Jan 29 '16 at 18:29

1 Answers1

1

You can use componentsSeparatedByCharactersInSet to break up your lines, then map each line breaking up your elements and finally map them to Int:

let strInput = "1 2\n3 4\n5 6\n7 8"

let numbers = strInput.componentsSeparatedByCharactersInSet(.newlineCharacterSet())
                      .map{$0.componentsSeparatedByString(" ")
                      .map{Int($0) ?? 0}} 

print(numbers)  // [[1, 2], [3, 4], [5, 6], [7, 8]]
itsji10dra
  • 4,603
  • 3
  • 39
  • 59
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571