arrays - 'SNstorelocation' 类型没有下标成员 - 我只是不明白
问题描述
几周以来,我一直在愉快地使用 Swift 编程——真的很享受,但我遇到了障碍。我用谷歌搜索,找不到解释。我设置了一个更简单的测试用例,它没有同样的问题。
我收到错误“类型'SNstorelocation'没有下标成员”,还有“类型'[SNstorelocation]的值?' 没有成员'追加'”。
我已经阅读了很多关于下标的内容,但我认为这不是问题所在。我想要一个结构数组,其中一个元素也是一个结构数组。我到处都看到了它,我的小测试用例也没问题。
所以我得出结论(可能是错误的!)不知何故我没有创建和排列。如果我有,它应该有一个索引来访问数据并且代码应该可以工作,但它没有。
这是我创建的小示例,我认为它与我的示例相同,但更简单,可以工作。
结构 test1 { var t1Item1: 整数?var t1Item2:字符串?var myArray = test2 } struct test2 { var t2Item1: Int? var t2Item2: 整数?
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 {
}
}
有人可以解释为什么第二个示例没有下标而第一个示例可以正常工作吗?我只是不明白 - 特别是因为第一次让似乎可以找到索引 - 我确信我刚刚做了一些愚蠢的事情!
TIA。
解决方案
Swift 编译器的模棱两可的错误报告……</p>
Atimestamp
不是布尔值,因此您需要将时间戳与某些内容进行比较。
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 团队提出一个错误。
作为风格点,大写变量很难阅读,因为它们看起来像类名。
推荐阅读
- powershell - 错误:制作:*** 没有规则来制作目标“makefile”。停止。使用 Powershell 和 Gnuwin32
- swift - Swift 可选语法
- r - 将指数修改的高斯拟合到 2D 数据
- php - PHP 致命错误:未捕获的错误:在 PHP 7.2.13 上调用未定义函数 idn_to_ascii()
- java - 将时间转换为 UTC 时间则相反
- c - 无法理解这是如何工作的
- json - 如何修复错误:“预计解码字典
但在这段代码中找到了一个数组? - visual-studio-2017 - 您可以在解决方案中混合使用 .NET Framework 4.* 吗?
- r - 带有索引(短符号)的子集 tibble (tidyverse)
- amazon-web-services - 在 Terraform 中销毁一个 EC2 实例?