Aymen Chouirfi Aymen Chouirfi - 5 months ago 11
Swift Question

Wrong results using Swift Array Filter

I am using XCode 7.3.1 (Swift 2.2). I got strange result when I applied a simple filter to my array.

// XCode Playground

var flightOne = Flight()
flighOne.airportTo = "Amesterdame"
flighOne.airportFrom = "Liege"
flighOne.tsDepart = 1

var flightTwo = Flight()
flighOne.airportTo = "Paris"
flighOne.airportFrom = "Rome"
flighOne.tsDepart = 2

var flightThree = Flight()
flighOne.airportTo = "Tunis"
flighOne.airportFrom = "New York"
flighOne.tsDepart = 3

var flightFour = Flight()
flighOne.airportTo = "Canada"
flighOne.airportFrom = "Germany"
flighOne.tsDepart = 4

let flights = [flighOne, flighTwo, flighThree, flighFour]

// it works fine if I change value != 0
let currentDate = 0

let incomingFlights = flights.filter({$0.tsDepart > currentDate})
"incomingFlights = \(incomingFlights.count)" // print "1" => Wrong !

let passedFlights = flights.filter({$0.tsDepart < currentDate})
"passedFlights = \(passedFlights.count)" // 0 => Good !


When I change the value of
currentDate
to any value different to
0
it works fine.

Answer

Your variables are incorrectly named which is most likely what is causing the issue. This should hopefully help:

// XCode Playground

var flightOne = Flight()
flightOne.airportTo = "Amesterdame"
flightOne.airportFrom = "Liege"
flightOne.tsDepart = 1

var flightTwo = Flight()
flightTwo.airportTo = "Paris"
flightTwo.airportFrom = "Rome"
flightTwo.tsDepart = 2

var flightThree = Flight()
flightThree.airportTo = "Tunis"
flightThree.airportFrom = "New York"
flightThree.tsDepart = 3

var flightFour = Flight()
flightFour.airportTo = "Canada"
flightFour.airportFrom = "Germany"
flightFour.tsDepart = 4

let flights = [flightOne, flightTwo, flightThree, flightFour]

// it works fine if I change value != 0
let currentDate = 0

let incomingFlights = flights.filter({$0.tsDepart > currentDate})
"incomingFlights = \(incomingFlights.count)" // print "1" => Wrong !

let passedFlights = flights.filter({$0.tsDepart < currentDate})
"passedFlights = \(passedFlights.count)" // 0 => Good !