如何将Swift.ArraySlice转换为Swift.Array?

时间:2017-12-21 10:19:03

标签: ios arrays swift slice

我从以下代码

收到错误
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!

1 个答案:

答案 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 { ...