I am trying to filter an array of dictionaries. The below code is the sample of the scenario i am looking for
let names = [
[ "firstName":"Chris","middleName":"Alex"],
["firstName":"Matt","middleName":""],
["firstName":"John","middleName":"Luke"],
["firstName":"Mary","middleName":"John"],
]
The final result should be an array for whom there is a middle name.
This did the trick
names.filter {
if let middleName = $0["middleName"] {
return !middleName.isEmpty
}
return false
}
Slightly shorter:
let result = names.filter { $0["middleName"]?.isEmpty == false }
This handles all three possible cases:
$0["middleName"]?.isEmpty evaluates to false and the predicate
returns true.$0["middleName"]?.isEmpty evaluates to true and the predicate
returns false.$0["middleName"]?.isEmpty evaluates to nil and the predicate
returns false (because nil != false).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With