Trying to read lines of integer from console separated by a single character space into a 2D array. I have tried using split(separator:maxSplits:omittingEmptySubsequences:)
, but it cannot be cast into an integer.
尝试从控制台读取由单个字符空间分隔的整数行到2D数组中。我曾尝试使用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
2 个解决方案
#1
0
try this one
试试这个
for i in 0...5 {
arr += readLine()!.components(separatedBy: " ").map{ Int($0)! }
}
#2
0
for i in 0...5 {
var aux = [Int]()
readLine()?.split(separator: " ").map({
aux.append(Int($0)!)
})
arr.append(aux)
}
#1
0
try this one
试试这个
for i in 0...5 {
arr += readLine()!.components(separatedBy: " ").map{ Int($0)! }
}
#2
0
for i in 0...5 {
var aux = [Int]()
readLine()?.split(separator: " ").map({
aux.append(Int($0)!)
})
arr.append(aux)
}