首页 > 解决方案 > 从数组中的多个特定结构中提取一个属性

问题描述

我的项目的一部分涉及比较 4 人的分数,找到最低的,然后输出那个玩家的名字。但现在我需要它来支持多个名称,我认为我已经成功完成了,但它输出了这些玩家的整个 Struct。例如:

["AppName.Player(name: "Bob", score: 2), AppName.Player(name: "John", score: 2)]

而我只是想要["Bob", "John"]或最好只是"Bob and John"

这是代码,其中winnerText控制显示的内容:

let players = [Player(name: "Bob", score: bobTotal), Player(name: "Ted", score: tedTotal), Player(name: "John", score: johnTotal), Player(name: "Rick", score: rickTotal)]
            
let minValue = players.min(by: { $0.score < $1.score })?.score ?? 0
let PlayersWithMinScore = players.filter { $0.score == minValue }
print(PlayersWithMinScore)

let winningPlayerIndex = players.indices.filter { players[$0].score == minValue }
print(winningPlayerIndex)
        
       
self.winnerText = "" + " won with " + "\(minValue)"
struct Player {
  let name: String
  let score: Int
}

标签: swiftui

解决方案


PlayersWithMinScore.map { $0.name }

以上将为您提供一个仅包含名称的数组。

从另一个答案中借用一个技巧(使用分隔符加入字符串数组“、”并添加“和”以加入 Swift 中的最后一个元素):

extension BidirectionalCollection where Element: StringProtocol {
    var sentence: String {
        count <= 2 ?
            joined(separator: " and ") :
            dropLast().joined(separator: ", ") + ", and " + last!
    }
}

然后你可以这样做:

PlayersWithMinScore.map { $0.name }.sentence

为您提供以逗号分隔的名称,然后在最后一个名称前加上“and”(例如“Bob and John”或“Bob、Tom 和“John”)。

附注:在 Swift 中,变量名通常以小写字母开头——playersWithMinScorePlayersWithMinScore


推荐阅读