Reputation: 6413
Is there anyway in swift we can get two inputs in single line.?
Like C
scanf("%d %d", &valueOne, &valueTwo);
so i can enter 10 20
readLine
let valueOne = readLine();
let valueTwo = readLine();
10
20
Upvotes: 3
Views: 3180
Reputation: 213
import Foundation
let text: String = readLine()! // input "1 2 3" in the console
let result: [Int] = text.split(separator: " ").map { Int($0)! } // [1, 2, 3]
print(result)
Use split()
to separate the return value of readLine()
and convert [String]
to [Int]
using map()
.
Upvotes: 1
Reputation: 6413
With the help of @Cœur, I wrote it as below, to get two inputs on same line in HackerRank
let values = readLine()?.characters.split(" ").flatMap(String.init)
Upvotes: 2
Reputation: 38667
You can easily split what is read into an Array.
let values = readLine()?.components(separatedBy: CharacterSet.whitespacesAndNewlines) ?? []
You can then store those in multiple variables in different ways. Here is an example:
let valueOne = values.count > 0 ? Int(values[0]) : nil
let valueTwo = values.count > 1 ? Int(values[1]) : nil
Upvotes: 4