[英]read line from console as input for 2D array in Swift iOS
Trying to read lines of integer from console separated by a single character space into a 2D array. 尝试从控制台读取由单个字符空间分隔成2D数组的整数行。 I have tried using
split(separator:maxSplits:omittingEmptySubsequences:)
, but it cannot be cast into an integer. 我试过使用
split(separator:maxSplits:omittingEmptySubsequences:)
,但是不能将其转换为整数。
The 2D array that has to be read from console as input looks like this 必须从控制台读取作为输入的2D数组如下所示
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
This is the code I tried 这是我尝试的代码
var arr = [[Int]]()
for i in 0 ... 5 {
var a = readLine()?.components(separatedBy: " ")
var arr[i] = [a?.split(separator: " ", maxSplits: 1, omittingEmptySubsequences: false)] as? Int
}
And the error is 错误是
cast from '[ArraySlice]?' to unrelated type 'Int' always fails
try this one 试试这个
for i in 0...5 {
arr += readLine()!.components(separatedBy: " ").map{ Int($0)! }
}
for i in 0...5 {
var aux = [Int]()
readLine()?.split(separator: " ").map({
aux.append(Int($0)!)
})
arr.append(aux)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.