-1

I tried to filter an ArraySlice<Float>to replace the values below -5000 and higher 5000 to -5000 and 5000. I can apply one condition but how I can apply both condition in a same time?
I want to add that if the value is higher than 5000, replace it with 5000, how I can do that?

 filteredData.append(contentsOf: data.map({ return $0 < -5000 ? -5000 : $0}))
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Robert kont
  • 165
  • 1
  • 8
  • 2
    That is called *clamping* – see [Standard way to “clamp” a number between two values in Swift](https://stackoverflow.com/questions/36110620/standard-way-to-clamp-a-number-between-two-values-in-swift) for various approaches. – Martin R Sep 25 '20 at 13:45

2 Answers2

0

You can just use an if-else statement to check both conditions

let filteredData = floatData.map { value -> Float in
    if value > 5000 {
        return 5000
    } else if value < -5000 {
        return -5000
    } else {
        return value
    }
}

Or you can use the combination of min and max to limit your values to a specified range.

let filteredData = floatData.map { value -> Float in max(min(value, 5000), -5000) }
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • this is wrong. you are returning the negative value for both conditions. Btw you could use pattern. match operator `-5000...5000 ~= $0 ? $0 : value` but thats not the case here – Leo Dabus Sep 25 '20 at 13:56
  • this also assumes that filteredData is empty which might not be true – Leo Dabus Sep 25 '20 at 13:59
  • @LeoDabus my bad, misread the question. As for omitting the `append`, I just created a minimal reproducible example in a playground, if OP needs the `append`, it should be easy to change. – Dávid Pásztor Sep 25 '20 at 14:05
  • Thank you so much guys – Robert kont Sep 25 '20 at 14:50
0

According to the task conditions, let's do it:

filteredData.append(contentsOf: data.map({ $0 < -5000 ? -5000 : $0 > 5000 ? 5000 : $0}))
Roman Ryzhiy
  • 1,540
  • 8
  • 5