无法使用类型为“(Int, () -> ())”的索引下标类型为“[xxx]”的值
Cannot subscript a value of type '[xxx]' with an index of type '(Int, () -> ())'
我有这个问题,访问数组索引时出错。索引应该是一个整数,但它不起作用。我最初尝试使用一个变量,但在这个例子中我将它更改为整数 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]
我认为你有额外的括号。试试这个:
let location = SNStore.Welland[index].locations[0]
if location.timestamp > 0 { /*do something*/ }
Swift 中的订阅是在幕后通过调用一个接受 Int
的特殊方法 subscript
完成的。所以当你写:
locations[0]
Swift 实际上是用 []
:
中的值调用 subscript
函数
locations.subscript(0)
您不能直接调用 subscript
,但它就在那里,您可以通过为它们实现 subscript
来为您自己的 类 定义自定义下标。
您将 Swift 与 locations[0]
后面的额外花括号 { }
混淆了。 Swift 将 { }
及其内容解释为带有签名 () -> ()
的闭包(不接受输入,returns 不输出)。由于 尾随闭包语法 ,Swift 然后将该闭包解释为 subscript
函数的第二个参数,该函数在 locations
上调用以执行索引.这个下标函数接受一个参数,一个 Int
,但是你传递了两个参数,一个 Int
和 () -> ()
闭包。这就是错误消息告诉您的内容。
修复方法是删除多余的 { }
:
let location = SNStore.Welland[index].locations[0]
if location.timestamp > 0 {
// do something
}
我有这个问题,访问数组索引时出错。索引应该是一个整数,但它不起作用。我最初尝试使用一个变量,但在这个例子中我将它更改为整数 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]
我认为你有额外的括号。试试这个:
let location = SNStore.Welland[index].locations[0]
if location.timestamp > 0 { /*do something*/ }
Swift 中的订阅是在幕后通过调用一个接受 Int
的特殊方法 subscript
完成的。所以当你写:
locations[0]
Swift 实际上是用 []
:
subscript
函数
locations.subscript(0)
您不能直接调用 subscript
,但它就在那里,您可以通过为它们实现 subscript
来为您自己的 类 定义自定义下标。
您将 Swift 与 locations[0]
后面的额外花括号 { }
混淆了。 Swift 将 { }
及其内容解释为带有签名 () -> ()
的闭包(不接受输入,returns 不输出)。由于 尾随闭包语法 ,Swift 然后将该闭包解释为 subscript
函数的第二个参数,该函数在 locations
上调用以执行索引.这个下标函数接受一个参数,一个 Int
,但是你传递了两个参数,一个 Int
和 () -> ()
闭包。这就是错误消息告诉您的内容。
修复方法是删除多余的 { }
:
let location = SNStore.Welland[index].locations[0]
if location.timestamp > 0 {
// do something
}