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

标签 arrays swift subscript

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

我收到错误“'SNstorelocation' 类型没有下标成员”,以及“'[SNstorelocation] 类型的值?'”没有成员 'append'”。

我已经阅读了大量关于订阅的内容,但我认为这不是问题所在。我想要一个结构数组,其中一个元素也是一个结构数组。我到处都看到它,我的小测试用例也没有问题。

所以我得出结论(也许是错误的!)我没有以某种方式创建和排列。如果我有,它应该有一个索引来访问数据并且代码应该可以工作,但它没有。

这是我创建的小示例,我认为它与我的示例相同,但更简单,而且有效。

结构测试1 { var t1Item1:整数? var t1Item2:字符串? var myArray = 测试 2 } 结构测试2 { var t2Item1:整数? 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 不是 bool 值,因此您需要将时间戳与某些内容进行比较。

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 团队提出错误。

作为风格要点,大写的变量读起来很糟糕,因为它们看起来像类名。

关于arrays - 类型 'SNstorelocation' 没有下标成员 - 我只是不明白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53601584/

相关文章:

javascript - Lodash _.filter 函数只能满足一个条件

swift - 另一个 View Controller 中属性的内联 KVO

运算符 [] 的 C++ 重载不适用于模板类

Swift 3 下标范围适用于第一个集群但不适用于中间

php - 在单列上按字母顺序对行数组进行排序,但一个值必须始终位于第一个

c - 使用 C 返回数组

c++ - 从函数 C++ 返回数组

swift - Swift 函数中可选泛型参数的默认值

ios swift siesta ResourceObserver resourceRequestProgress 从未调用过

java - 向 JFrame 上图形中的字符串添加下标和字体