• notice
  • Congratulations on the launch of the Sought Tech site

Swift collection type higher-order functions

Use of filter and reduce (swift 5.3)

filter

Filtering, the elements in the array can be filtered once according to a certain rule.

let numbers = [1, 3, 5, 7, 9]
let filterNumbers = numbers.filter {$0 <5}
print(filterNumbers)

The output is as follows

[1, 3]

reduce

Calculation, you can calculate the elements of the array

let animals1 = ["Dog", "Cat", "Pig"]
let string = animals1.reduce("Dog", {
     // $0: result, $1: the value of the array
     return $0 == "Cat"? $1: $0 + "," + $1
})
print(string)

The output result is as follows

Dog,Dog,Cat,Pig


Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+