Reputation: 1223
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.
Upvotes: 3
Views: 6815
Reputation: 539965
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
).Upvotes: 4
Reputation: 1223
This did the trick
names.filter {
if let middleName = $0["middleName"] {
return !middleName.isEmpty
}
return false
}
Upvotes: 6
Reputation: 40963
You can also use the nil-coalescing operator to express this quite succinctly:
let noMiddleName = names.filter { !($0["middleName"] ?? "").isEmpty }
This replaces absent middle names with empty strings, so you can handle either using .isEmpty
(and then negate if you want to fetch those with middle names).
You can also use optional chaining and the nil-coalescing operator to express it another way:
let noMiddleName = names.filter { !($0["middleName"]?.isEmpty ?? true) }
$0["middleName"]?.isEmpty
will call isEmpty
if the value isn’t nil
, but returns an optional (because it might have been nil
). You then use ??
to substitute true
for nil
.
Upvotes: 3
Reputation: 1223
This also works fine
names.filter {
if let middleName = $0["middleName"] {
return middleName != ""
}
return false
}
Upvotes: 1