swiftui - 从数组中的多个特定结构中提取一个属性
问题描述
我的项目的一部分涉及比较 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
推荐阅读
- c# - C# 启动导入进程以在后台运行
- amazon-web-services - 在 AWS 中,S3 和 IAM 权限是否不同?
- ruby-on-rails - 为什么没有将 nil 隐式转换为 Hash?
- python - Pycharm“请选择App Engine SDK目录”问题
- r - 在 for 循环 (R) 中使用字符向量
- java - 如何在列表中添加每个项目的第二个元素?
- javascript - 从 Youtube API 文档中复制的示例不起作用
- php - 如何在 Laravel 中使用子查询获得排名?
- java - 使用 Spring Boot 2.3.4.RELEASE Jackson2ObjectMapper 将 LocalDate 序列化为时间戳
- c# - 在 ServiceProvider 中使用时,如何防止我的 DbContext 用完可用的池连接?