通过map()将String转换为Int

时间:2018-04-11 19:52:44

标签: swift compiler-errors type-conversion

我有一个输入(String):"1 * 2 + 34 - 5"我希望将其拆分为数组,然后将“convertible”元素转换为整数。我的代码如下所示:

let arr: [Any] = readLine()!.split(separator: " ").map {Int($0) != nil ? Int($0) : $0}

分裂不是问题,但我不知道为什么映射不能正常工作。我收到错误:

error: cannot invoke initializer for type 'Int' with an argument list of type '((AnySequence<String.Element>))'
note: overloads for 'Int' exist with these partially matching parameter lists: (Float), (Double), (Float80), (Int64), (Word), (NSNumber), (CGFloat)

我尝试以另一种方式做同样的事情,初始化新数组:

let arr = readLine()!.split(separator: " ")
let newArray: [Any] = arr.map {Int($0) != nil ? Int($0) : $0}

但它也给我一个错误:

error: 'map' produces '[T]', not the expected contextual result type '[Any]'

令我感到惊讶的是,当我尝试使用for循环时,它完美地运行:

let arr = readLine()!.split(separator: " ")
var newArray = [Any]()
for x in arr
{
    if Int(x) != nil {newArray.append(Int(x)!)}
    else {newArray.append(x)}
}
print(newArray)

输出:[1, "*", 2, "+", 34, "-", 5]

有人可以向我解释这里发生了什么吗?我的意思是如果所有3个代码都做同样的事情那么为什么只有“for loop”工作正常?

1 个答案:

答案 0 :(得分:1)

您需要指定map块的返回类型为Any,而不是编译器推断的类型(Int),例如< / p>

let fullString = "1 * 2 + 34 - 5"
let elements = fullString
    .components(separatedBy: " ")
    .map { Int($0) ?? $0 as Any}