如何在Swift中访问第二个和第三个元素

问题描述 投票:0回答:1

嗨,我想显示前三名玩家的分数,但即使可以访问第一个元素,以下代码也不起作用。如果你能帮忙那就太好了。谢谢。

struct ContentView: View {
    
    @Query(sort: \PlayerItem.playerScore, order: .reverse) var playerItems: [PlayerItem]
    }
var body: some View {

// this works 
Text("Your best score : \(playerItems.first?.playerScore ?? 0)")

// this does not works 
Text("Your second best score: \(playerItems.second?.playerScore ?? 0)")

// this also does not works 
Text("Your second best score: \(playerItems.second?.playerScore )")

// this also does not works
Text("Your second best score: \(playerItems[1].playerScore )")
ios swift
1个回答
0
投票

如果想显示所有分数,您可以迭代每个分数,如下所示:

struct ContentView: View {
    
    @Query(sort: \PlayerItem.playerScore, order: .reverse) var playerItems: [PlayerItem]
}
    
    var body: some View {
        List {
            ForEach(playerItems, id: \.self) { item in
                Text(item.playerScore)
            }
        }
    }
}

如果您只想要特定数量的分数,例如 3,您可以使用

FetchDescriptor
来限制获取计数,请参阅下面的示例:

struct ContentView: View {
    
    static var descriptor: FetchDescriptor<PlayerItem> {
        var descriptor = FetchDescriptor<PlayerItem>(sortBy: [SortDescriptor(\.playerScore, order: .reverse)])
        descriptor.fetchLimit = 3
        return descriptor
    }
    
    @Query(descriptor) var playerItems: [PlayerItem]
    
    var body: some View {
        List {
            ForEach(playerItems, id: \.self) { item in
                Text(item.playerScore)
            }
        }
    }
}

并且您只会显示订购的前 3 个分数。

© www.soinside.com 2019 - 2024. All rights reserved.