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

只愿长相守 提交于 2019-12-01 09:15:41

Subscripting in Swift is done behind the scenes by calling a special method subscript which takes an Int. So when you write:

locations[0]

Swift is really calling the subscript function with the value inside of []:

locations.subscript(0)

You can't call subscript directly, but it is there and you can define custom subscripting for your own classes by implementing subscript for them.

You are confusing Swift with the extra curly braces { } which follow locations[0]. Swift interprets the { } and their contents as a closure with signature () -> () (takes no input, returns no output). Because of trailing closure syntax, Swift then interprets that closure as a second argument to the subscript function that is called on locations to perform the indexing. This subscripting function takes one argument, an Int, but you are passing two arguments, an Int and the () -> () closure. That is what the error message is telling you.

The fix is to remove the extra { }:

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

I think you have extra parentheses. Try this:

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

 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!