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

标签 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
      }
   }

Could not cast value of type 'Swift.ArraySlice' (0x107ef4b40) to '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!

最佳答案

真正的错误原因在这一行

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

关于ios - 如何将 Swift.ArraySlice 转换为 Swift.Array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47922726/

相关文章:

ios - 如何在没有 View Controller 的情况下将选项卡栏项添加到 UITabBarController?

javascript - JS/Jquery - 通过键从数组中删除多个元素

java - 用于动态字节存储的碎片数组的缺点

javascript - 动态行创建挖空js

json - 在 Swift 中迭代解码 JSON 的字典键

ios - 从当前日期到特定日期的倒计时

ios - 如何从 facebook sdk 4 快速获取用户电子邮件

iphone - 应用商店是否拒绝不支持多方向的IPAD应用

iOS Xcode : Warn about methods not in minimum target SDK

iphone - 如何实现如图所示的 UIPickerView,并带有组件标题?