我从以下代码
收到错误if(currentArgument == "")
{
numberOfArgInCurrentFunction -= 1
var lastExp = expressionStack.last!
lastExp["ArgList"] = (lastExp["ArgList"] as! [String]).dropLast()
expressionStack.remove(at: expressionStack.count - 1)
expressionStack.append(lastExp)
if(lastExp.count > 0)
{
let argList:[String:Any] = expressionStack.last!
currentArgument = (argList["ArgList"] as! [String]).last! // ***Error on this line
}
}
无法转换类型' Swift.ArraySlice' (0x107ef4b40)到了Swift.Array' (0x107ef2538)。
现在想知道有没有办法将Swift.ArraySlice转换为Swift.Array或从Swift.ArraySlice获取最后一个元素的方法
编辑 - 复制
如果我尝试转换使用波纹管代码
let slice = argList["ArgList"] as ArraySlice //*** Cannot convert value of type 'Any?' to type 'ArraySlice<_>' in coercion because
let array:[String] = Array(slice)
currentArgument = array.last!
答案 0 :(得分:2)
错误的实际原因在于此行
lastExp["ArgList"] = (lastExp["ArgList"] as! [String]).dropLast()
您正在重新分配类型ArraySlice
,而不是意图Array
已经那里,您必须创建一个新数组
lastExp["ArgList"] = Array((lastExp["ArgList"] as! [String]).dropLast())
永远不会检查字符串和集合类型是否与.count == 0
空虚。有一个优化的isEmpty
属性,并且不要在Swift的括号中包含if
表达式:
if !lastExp.isEmpty { ...