我正在玩HackerRank。我需要从行读取到整数数组的问题之一:
A=(1,2,3)
B=(1,4,7)
我试过了:
let line = readLine()
print(line)
但是我收到了这个错误:
solution.swift:2:7: warning: expression implicitly coerced from 'String?' to Any
print(line)
^~~~
solution.swift:2:7: note: provide a default value to avoid this warning
print(line)
^~~~
?? <#default value#>
solution.swift:2:7: note: force-unwrap the value to avoid this warning
print(line)
^~~~
!
solution.swift:2:7: note: explicitly cast to Any with 'as Any' to silence this warning
print(line)
^~~~
as Any
你们中的任何人都知道我怎么读线并获得数组?
我真的很感谢你的帮助
答案 0 :(得分:2)
let line = readLine()!
print(line)
//To Array, should work. Wrote it real quick
let array = readLine()!.characters.split(" ").map( { String($0)! } )
答案 1 :(得分:0)
如果您要将String从readLine转换为Integer数组,则可以使用:
let array = readLine()!.split{ $ == " " }.map{ Int(String($0)) }
您不能:
let array = readLine()!.split{ $ == " " }.map{Int($0)}
因为$0
是一个可选的字符数组类型(我认为),Int不会解析。
答案 2 :(得分:0)
我用下面的线为我工作。
var arr = readLine()!.components(separatedBy: " ").map{(a: String)->(Int) in
return Int(a)!
}