Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a range filter on an array

I'm running into trouble finding an efficient way to filter my data. What I got so far:

A structure like this:

struct BasicData {
    let n0 : Double!
    let n1 : Double!
    let n2 : Double!
}
var basicData = [BasicData]()

After appending the Array using:

basicData.append(BasicData(n0: 55.15, n1: 5.1, n2: 2))
basicData.append(BasicData(n0: 2, n1: 2.1, n2: 25))
basicData.append(BasicData(n0: 45.15, n1: 5.1, n2: 15))

I want to create a new Array that contains all elements whose n0 > 5 && n0 < 50 and n2 > 7 && n2 < 40

like image 422
user3138007 Avatar asked Sep 01 '26 02:09

user3138007


2 Answers

As already mentioned in comments by @Hamish you should make your structs properties non-optionals:

struct BasicData {
    let n0, n1, n2: Double
}

To filter your array you can use the range pattern operator ~=. If you need to make your range start from the first fraction number greater than the lower bound of your range you can use Double property .nextUp as follow:

let filtered = basicData.filter { 
    5.nextUp..<50 ~= $0.n0 && 7.nextUp..<40 ~= $0.n2 
}
like image 154
Leo Dabus Avatar answered Sep 03 '26 22:09

Leo Dabus


let filteredData = basicData.filter({$0.n0 > 5 && $0.n0 < 50 && $0.n2 > 7 && $0.n2 < 40})
like image 26
Faisal Khalid Avatar answered Sep 04 '26 00:09

Faisal Khalid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!