0

I have a class like this

class ValueTimestamp {
  let value: Double
  let timestamp : Double
  init(value:Double, timestamp:Double) {
    self.value = valuer
    self.timestamp = timestamp
  }
}

Then I have an array filled with ValueTimestamp objects. Let's call this, myArray.

Now I want to manipulate the array, to extract, for example the elements with values bigger than 10.

Because I am new to swift, I would do this:

// this will create an array with Doubles
let sub = myArray.map($0.value > 10)

var newArray : [ValueTimestamp] = []
for i in 0..< myArray.count {
  let newValue = ValueTimestamp.init(value:sub[i], timestamp:myArray[i])
  newArray.append(newValue)
}

and now I have newArray that contains the elements from myArray with values bigger than 10.

Is there any magic command using .map, .flatmap or whatever that can do this?

1 Answer 1

2

What you looking for is filter method:

public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]

It takes as parameter closure, which take 1 element and return true if element should be added in resulting array or false if it should be filtered out.

Your code:

let biggerThem10 = myArray.filter { $0.value > 10 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.