我如何计算A队的teamMember?
class BasketBallTeam {
var teamName: String
var teamMember: [String]
init(teamName: String, teamMember: [String]) {
self.teamName = teamName
self.teamMember = teamMember
}
}
let highSchoolTeam: [BasketBallTeam] = [
BasketBallTeam(teamName: "A", teamMember: [
"John", "Sam", "Tom", "Ricky", "George"
]),
BasketBallTeam(teamName: "B", teamMember: [
"Jason", "Michael", "Daniel", "Henry", "David", "Luke"
]),
]
答案 0 :(得分:1)
只需count
。
由于highSchoolTeam
是一个数组,因此您必须获取first
项
let numberOfMembers = highSchoolTeam.first?.teamMember.count
请以teamMember
(甚至是teamMembers
)的复数形式命名members
,以表示数组
答案 1 :(得分:0)
您可以按以下方式获得每个团队的人数:
for team in highSchoolTeam {
print(team.teamMember.count)
}
答案 2 :(得分:0)
如果您经常这样做,最好创建一个字典,使您可以轻松按团队名称访问团队:
struct BasketBallTeam {
var name: String
var members: [String]
init(name: String, members: [String]) {
self.name = name
self.members = members
}
}
let highSchoolTeams: [BasketBallTeam] = [
BasketBallTeam(name: "A", members: [
"John", "Sam", "Tom", "Ricky", "George"
]),
BasketBallTeam(name: "B", members: [
"Jason", "Michael", "Daniel", "Henry", "David", "Luke"
]),
]
let teamsByName = Dictionary(uniqueKeysWithValues:
highSchoolTeams.lazy.map { team in (key: team.name, value: team) })
这使得按名称快速查找任何团队:
let teamA = teamsByName["A"]
let teamASize = teamA?.members.count
print(teamASize as Any)
如果您只需要这样做一次,则可以使用first(where:)
:
let teamA = highSchoolTeams.first(where: { $0.name == "A"})
答案 3 :(得分:0)
您可以简单地使用
first(_:)
,获得highSchoolTeam
,其中team
。teamName == "A"
,从步骤1中获得的count
中获得teamMember
的总数count
。就像这样
teamMembers