Map only non-nil values
For Swift 3.0 and above:
return sectionJsons.compactMap { DynamicSection($0) }
You can use flatMap
:
return sectionJsons.flatMap { DynamicSection($0) }
Example:
struct Foo {
let num: Int
init?(_ num: Int) {
guard num % 2 == 0 else { return nil }
self.num = num
}
}
let arr = Array(1...5) // odd numbers will fail 'Foo' initialization
print(arr.flatMap { Foo($0) }) // [Foo(num: 2), Foo(num: 4)]
// or, point to 'Foo.init' instead of using an anonymous closure
print(arr.flatMap(Foo.init)) // [Foo(num: 2), Foo(num: 4)]
Whenever you see a chained filter
and map
, flatMap
can generally be used as a good alternative approach (not just when using the filter to check nil
entries).
E.g.
// non-init-failable Foo
struct Foo {
let num: Int
init(_ num: Int) {
self.num = num
}
}
let arr = Array(1...5) // we only want to use the even numbers to initialize Foo's
// chained filter and map
print(arr.filter { $0 % 2 == 0}.map { Foo($0) }) // [Foo(num: 2), Foo(num: 4)]
// or, with flatMap
print(arr.flatMap { $0 % 2 == 0 ? Foo($0) : nil }) // [Foo(num: 2), Foo(num: 4)]