Home > Software design >  Comparing struct values which are inside class
Comparing struct values which are inside class

Time:09-24

I've class and inside of a class got struct GoalsDifference, in that struct there are two propertys: scoredGoal and passedGoal which's value is passed by me. I've declared two variables with this class and struct and put them in array. Now I want to get into the array and compare the first variable's scoredGoal to the other one ( as well as passedGoals to each other )

class Team: Base {
    var goalsDifference: GoalsDifference?
    
    override init(name:String){
        super.init(name: name)
    }
    
    convenience init(name:String, goalsDifference:GoalsDifference){
        self.init(name:name)
        self.goalsDifference = goalsDifference
    }
    
    struct GoalsDifference {
        var scoredGoal:Int
        var passedGoal:Int
    }
}
var team1 = Team(name:"Team one", goalsDifference: .init(scoredGoal: 3, passedGoal: 5))
var team2 = Team(name:"Team two", goalsDifference: .init(scoredGoal: 3, passedGoal: 2))
var twoTeams = [team1,team2]

I tried to do it with .filter method but it returns an error : Contextual closure type '(Team) throws -> Bool' expects 1 argument, but 2 were used in closure body

twoTeams[0..<teamsCount].filter { $0.goalsDifference?.scoredGoal ?? "" > $1.goalsDifference?.scoredGoal ?? ""}

CodePudding user response:

This gets a little cumbersome since goalDifference is optional but here is a solution with a function that compares self with another team. I assume that this is sports related and that goals always start at 0.

extension Team {
    private static let emptyGoalsDifferenc = GoalsDifference(scoredGoal: .zero, passedGoal: .zero)
    func best(goals: KeyPath<GoalsDifference, Int>, comparing other: Team) -> Team? {
        let ownDifference = self.goalsDifference ?? Self.emptyGoalsDifferenc
        let otherDifference = other.goalsDifference ?? Self.emptyGoalsDifferenc

        let ownGoals = ownDifference[keyPath: goals]
        let otherGoals = otherDifference[keyPath: goals]

        if ownGoals == otherGoals { return nil }
        return ownGoals > otherGoals ? self : other
    }
}

Example

var team1 = Team(name:"Team one", goalsDifference: .init(scoredGoal: 3, passedGoal: 5))
var team2 = Team(name:"Team two", goalsDifference: .init(scoredGoal: 3, passedGoal: 2))

let bestScored = team1.best(goals: \.scoredGoal, comparing: team2)
let bestPassed = team1.best(goals: \.passedGoal, comparing: team2)
  • Related