如何将属性项计数为类内的数组?

时间:2019-06-18 04:31:16

标签: arrays swift class

我如何计算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"
    ]),
]

4 个答案:

答案 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)

您可以简单地使用

  1. {{1}上的first(_:),获得highSchoolTeam,其中team
  2. {{1}上的teamName == "A",从步骤1中获得的count中获得teamMember的总数count

就像这样

teamMembers