user3138007
user3138007

Reputation: 637

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

Upvotes: 3

Views: 180

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236518

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 
}

Upvotes: 4

Faisal Khalid
Faisal Khalid

Reputation: 650

let filteredData = basicData.filter({$0.n0 > 5 && $0.n0 < 50 && $0.n2 > 7 && $0.n2 < 40})

Upvotes: 3

Related Questions