无法用索引类型为((Int,()->())'的索引下标类型为[[xxx]]的值

时间:2018-12-04 18:32:02

标签: swift indexing subscript

我有这个问题,访问数组索引时出错。索引应为整数,但不起作用。我最初尝试使用变量,但是在此示例中,我将其更改为整数0,只是为了表明它不是问题所在的变量。

   let location = SNStore.Welland[index].locations[0] {
                    if location.timestamp > 0 {

                    }
                }

错误是:

 Cannot subscript a value of type '[LocationStore]' with an index of type '(Int, () -> ())'

那么有人可以解释为什么数组不希望索引为int吗?它很奇怪,我听不懂。

我在快速帮助中检查了位置声明,它正确显示了在结构中如何声明位置。 (在结构中,它的末尾带有花括号以将其初始化为空。)

var locations: [LocationStore]

2 个答案:

答案 0 :(得分:2)

通过调用特殊方法subscript并使用Int在Swift中进行下标。所以当你写:

locations[0]

Swift确实使用subscript内部的值调用[]函数:

locations.subscript(0)

您不能直接调用subscript,但是它在那里,您可以通过为自己的类实现subscript来为自己的类定义自定义下标。

您将Swift与{ }后的多余花括号locations[0]混淆了。 Swift将{ }及其内容解释为带有签名() -> ()的闭包(不输入,不返回输出)。由于采用跟踪闭包语法,Swift然后将该闭包解释为subscript函数的第二个参数,该函数在locations上被调用以执行索引。该下标函数采用一个参数Int,但是您要传递两个参数Int() -> ()闭包。这就是错误消息告诉您的内容。

解决方法是删除多余的{ }

let location = SNStore.Welland[index].locations[0]
if location.timestamp > 0 {
    // do something
}

答案 1 :(得分:1)

我认为您还有多余的括号。试试这个:

 let location = SNStore.Welland[index].locations[0]
 if location.timestamp > 0 {

 }