Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if the element exists in the array, and then replace between two arrays Swift

I have a class "Players", and a class "Team". I created two array of Strings calling player1.name, player2.name, etc.
one array with main players and the other array with secondary players

Class:

class Players {
    let name: String
    let number: int
    var position:PositionPlayer
    var birth: Date
    let nationality: String
    var height: Double 
    var weight: int
    init(name: String, number: Int, position: PositionPlayer, birth: Date, height: Double, weight: Int) {
        self.name = name
        self.number = number
        self.position = position
        self.birth = birth
        self.nationality = nationality
        self.height = height
        self.weight = weight
    }

Class Team is empty (just doing the function on it)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Arrays:

var mainPlayers: [String] = []
var secondaryPlayers: [String] = []

add elements in arrays:

mainPlayers.append("\(player1.name)")

How do I make a function in class "Team" that checks the elements of the arrays and does the substitution between the 2 arrays?

e.g. I have 3 main players and 3 secondary players, and I want to put player 4 (secondary player) in place of player 1.

>Solution :

If the order of the collection doesnt matter you should use a set to make sure there is no duplicated players in your collection:

var mainPlayers: Set = ["player1", "player2", "player3"]
var secondaryPlayers: Set = ["player4", "player5", "player6"]

if let oldMember = mainPlayers.remove("player1"),
    let newMember = secondaryPlayers.remove("player4"),
   mainPlayers.insert(newMember).inserted,
   secondaryPlayers.insert(oldMember).inserted {
    print("oldMember", oldMember)   // player1
    print("newMember", newMember)   // player4
    print(mainPlayers)       // ["player3", "player4", "player2"]
    print(secondaryPlayers)  // ["player1", "player5", "player6"]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading