【问题标题】:"Cannot subscript a value of type '[String]'" and "Cannot assign value of type 'ArraySlice' to type '[String]?'" errors in SwiftSwift 中的“无法下标 '[String]' 类型的值”和“无法将 'ArraySlice' 类型的值分配给类型 '[String]?'”错误
【发布时间】:2016-01-18 23:01:07
【问题描述】:

Xcode 给了我一个毫无意义的错误:

let command = ["", "", ""]
let task = NSTask()
task.arguments = command[1...command.count-1]

错误:无法为“[String]”类型的值下标

为什么?

如果我把它分解:

let command = ["", "", ""]
let a = command[1...command.count-1]
let task = NSTask()
task.arguments = a

错误:无法将类型“ArraySlice”的值分配给类型“[String]?”

为什么 Xcode 在物理上无法生成有意义的错误消息?当然,原始代码并没有复杂到让编译器感到困惑!

另外,为什么我不能将 ArraySlice 分配给 Array 类型的变量?

【问题讨论】:

    标签: swift compiler-errors swift2


    【解决方案1】:

    因为

    let a = command[1...command.count-1]
    task.arguments = a
    

    你在 "a" ArraySlice 中得到 arrayslice,但 task.arguments 采用 [String]?

    现在,您需要将 arrayslice 转换/转换为字符串数组。 使用:

    let a: [String] = Array(command[1...command.count-1])
    

    在这里,我们将arrayslice 转换为[String] 类型的数组。

    【讨论】:

      【解决方案2】:

      ArraySlice 只是指向内存中现有Array 的(部分)。 “子数组”还没有被复制分配到另一个内存位置,因为切片只是描述了内存中已经存在的数组的子集。但是,要将其用作NSTask.arguments 设置器的Array,您需要将ArraySlice 强制转换为Array(它会强制复制分配您的“子数组”,然后将其发送到属性@ 的设置器) 987654327@).

      let command = ["", "", ""]
      let task = NSTask()
      task.arguments = Array(command[1...command.count-1])
      

      另外,我同意 XCode 在报告错误时并不总是正确的。您确实在这里采用了正确的方法;分解您报告的错误表达式,在实际错误消息被提供给您之后。我实际上认识到掩蔽错误 "Cannot subscript a value of type '[T]'" 是我自己偶然发现的,而实际上随后的函数调用分配是错误的真正根源.

      【讨论】:

        【解决方案3】:

        当不确定表达式类型时(尤其是当编译器抱怨时),您可以做的一件事是使用 dynamicType 属性来确定实际生成的类型。

        print("\(command[1...command.count-1].dynamicType)")
        // gives ArraySlice<String>.Type
        
        print("\(command.dynamicType)"
        // gives Array<String>.Type
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多