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

Time:02-12

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)

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.

CodePudding user response:

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"]
}

If the order of the collection matter the array approach should look like this:

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

if let oldMemberIndex = mainPlayers.firstIndex(of: "player1"),
    let newMemberIndex = secondaryPlayers.firstIndex(of: "player4"),
    case let oldMember = mainPlayers.remove(at: oldMemberIndex),
    case let newMember = secondaryPlayers.remove(at: newMemberIndex) {
    mainPlayers.insert(newMember, at: oldMemberIndex)
    secondaryPlayers.insert(oldMember, at: newMemberIndex)
    print("oldMember", oldMember)   // player1
    print("newMember", newMember)   // player4
    print(mainPlayers)       // ["player4", "player2", "player3"]
    print(secondaryPlayers)  // ["player1", "player5", "player6"]
}
  • Related