Home > front end >  Swift - throw error if the element doesn't exist in the array
Swift - throw error if the element doesn't exist in the array

Time:02-23

I've two arrays of int, with 3 elements each. I'm trying to throw an error if the int number I received with func doesn't exist in the arrays

func switch(a: Int, b: Int) throws -> Void {

   if a < 0 || b < 0 || a > arrayA.count || b > arrayB.count {
 
       throw SwitchError.error
}

I'm trying to use count to do this, but always return the error that numbers don't exist in the array even though they are there... is there another way to achieve this?

class SoccerPlayer {                   
    let name: String
    let number: Int
    init(name: String, number: Int) {
        self.name = name
        self.number = number
    }
}

class Team {
    var nameTeam: String
    var arrayA: [SoccerPlayer] = []
    var arrayB: [SoccerPlayer] = []
    init(nameTeam: String, arrayA: [SoccerPlayer], arrayB: [SoccerPlayer]) {
        self.nameTeam = nameTeam
        self.arrayA = arrayA
        self.arrayB = arrayB
    }
    func switch(a: Int, b: Int) throws -> Void {
        if a < 0 || b < 0 || a > arrayA.count || b > arrayB.count {
            throw SwitchError.error
        } 
    }
}

CodePudding user response:

With the additional information from the comments, it looks like you have arrays like this:

class SoccerPlayer {
  var name : String
  var number : Int
  //etc
}

var arrayA : [SoccerPlayer] = ...
var arrayB : [SoccerPlayer] = ...

Given that setup, if you want to check whether the arrays contains an element where the number property is matched, you could do either of these:

func check(a: Int, b: Int) throws {
    if a < 0 || b < 0 || !arrayA.map(\.number).contains(a) || !arrayB.map(\.number).contains(b) {
        throw SwitchError.error
    }
    //etc
}

func check(a: Int, b: Int) throws {
    if a < 0 || b < 0 || !arrayA.contains(where: { $0.number == a}) || !arrayB.contains(where: { $0.number == b }) {
        throw SwitchError.error
    }
    //etc
}

The first makes a new array of just the numbers and checks it for the element -- the second checks without making the interim array. These are functionally the same, but may have different performance characteristics with larger arrays.

  • Related