类型 'SNstorelocation' 没有下标成员 - 我只是不明白



几周来,我一直在Swift中愉快地编程——真的很享受,但我遇到了障碍。我在谷歌上搜索了一下,找不到解释。我设置了一个简单得多的测试用例,它没有同样的问题。

我得到错误"类型'SNstorelocation'没有下标成员",并且"类型'[SNstorelocation]?'的值没有成员'append'"。

我读过很多关于下标的书,但我认为这不是问题所在。我想要一个structs数组,其中一个元素也是structs的数组。我到处都能看到它,我的小测试用例也没问题。

所以我得出结论(也许是错误的!(,不知何故,我还没有创建和数组。如果我有,它应该有一个索引来访问数据,代码应该可以工作,但它没有。

这是我创建的一个小例子,我认为它和我的例子一样,但更简单,有效。

结构测试1{var t1Item1:Int?var t1Item2:字符串?var myArray=测试2}结构测试2{var t2Item1:Int?var t2Item2:Int?

init(v1: Int, v2: Int) {
self.t2Item1 = v1
self.t2Item2 = v2
}
}

我可以做所有正常阵列的事情:

var myVar = [test1]()
var newItem = test1()
newItem.t1Item1 = 1
newItem.t1Item2 = "Hi"
myVar.append(newItem)
let myCount = myVar[0].myArray.count

作为我的例子(只删除了结构中的几个元素,以保持简单和简短(

struct SNStoreItemGroups: Codable {
var Welland: [SNStoreItem]
var Other: [SNStoreItem]
init() {
self.Welland = []
self.Other = []
}
}
struct SNStoreItem: Codable {
var locations =  [SNstorelocation]()
var customerName: String?
var customerPhone: String?
var customerEmail: String?
var notes: String?

}
struct SNstorelocation: Codable {
let longitude: Double
let latitude: Double
let country: String
let user: Int
let timestamp: Double = Date().timeIntervalSinceReferenceDate
init(_ lon: Double, _ lat: Double, _ ISOcountry: String, _ UserID: Int) {
self.longitude = lon
self.latitude = lat
self.country = ISOcountry
self.user = UserID
}
}
var mySNData: SNStoreItem?
var SNStore: SNStoreItemGroups = SNStoreItemGroups()
// Some code to populate the SNStore

if let locIndex = SNStore.Welland[index].locations.index(where: { $0.longitude == MyLongitude }) {
// This then causes the error
// "Type 'SNstorelocation' has no subscript members"
if SNStore.Welland[index].locations[locIndex].timestamp {
}
}

有人能解释一下为什么第二个例子没有下标,而第一个还可以吗?我只是不明白——尤其是因为第一个let似乎可以找到索引——我确信我只是做了一些愚蠢的事情!

TIA。

Swift编译器的模糊错误报告…

timestamp不是布尔值,因此需要将时间戳与某些内容进行比较。

if let locIndex = mySNStore.welland[index].locations.index(where: { $0.longitude == 0.1234 }) {
if mySNStore.welland[index].locations[locIndex].timestamp == Double(42) {
}
}

您可以看到正确的错误和问题:

let location = mySNStore.welland[index].locations[locIndex]
if location.timestamp {
}

你可以向Swift团队提出这个问题。

作为一个风格点,大写变量读起来很可怕,因为它们看起来像类名。

最新更新