簡體   English   中英

如何在結構 Swift 中獲取數組的第一個索引

[英]How to get firstindex of array in struct Swift

嗨,我有一個這樣的結構

struct OrderCaches: Codable {
    var food, drink: [Food]?
}


struct Food: Codable{
    var id: Int?
    var name: String?
    var quantity: Double?
    var notes: String?
}

我想獲得第一個索引,其中 id = productList[indexPath.row].id

我試過:

let index = OrderCaches.firstIndex(where: {$0.food.id == productList[indexPath.row].id})

但不起作用我收到此錯誤“ '[Food] 類型的值?' 沒有成員'id' ”。 如何獲得第一個索引? 謝謝

function firstIndex不是 static 成員,而是實例成員,因此您必須創建OrderCache的實例才能獲取索引,如下所示:

let orderCaches = OrderCaches(food: [], drink: [])
let index = orderCaches.food?.firstIndex(where: { $0.id == productList[indexPath.row].id })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM