我的项目的一部分包括比较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
}
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中,变量名通常以小写字母开头-playersWithMinScore
比PlayersWithMinScore
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句