Daniel Hall
Daniel Hall

Reputation: 854

Swift 4.2 closures

Hi I'm learning swift I have an exercise on closures used to filter collections

I have two simple closures that are used to filter and map a dictionary

let myDict: [String: Int] = ["Dan":38, "Kira":2, "Olga":33, "Jess":10, "Bobo":4]

let filteredMyDict = myDict.filter {
    return $0.value < 5
}
print(filteredMyDict)

let filteredNames = filteredMyDict.map {
    return $0.key
}

print(filteredNames)

Is it possible to chain the filter and map statement , if so how.

That

Upvotes: 2

Views: 148

Answers (1)

Martin R
Martin R

Reputation: 539745

You can chain filter and map

let filteredNames = myDict.filter { $0.value < 5 }
    .map { $0.key }

or use compactMap to get the result with a single traversal of the dictionary:

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

In your case:

let filteredNames = myDict.compactMap {
    $0.value < 5 ? $0.key : nil
}

Upvotes: 6

Related Questions