Filtering an array based on null value in Swift
I am trying to filter an array of dictionaries. Below is the example script I am looking for
let names = [
[ "firstName":"Chris","middleName":"Alex"],
["firstName":"Matt","middleName":""],
["firstName":"John","middleName":"Luke"],
["firstName":"Mary","middleName":"John"],
]
The end result should be an array that has a middle name.
source to share
You can also use the nil-coalescing operator to express this rather succinctly:
let noMiddleName = names.filter { !($0["middleName"] ?? "").isEmpty }
This replaces the missing middle names with empty strings, so you can handle either with .isEmpty
(and then deny if you want to get them with middle names).
You can also use optional chaining and the nil-coalescing operator to express it differently:
let noMiddleName = names.filter { !($0["middleName"]?.isEmpty ?? true) }
$0["middleName"]?.isEmpty
will call isEmpty
if value isnt nil
, but return optional (as it could be nil
). Then you use the ??
replacement true
for nil
.
source to share
Slightly shorter:
let result = names.filter { $0["middleName"]?.isEmpty == false }
This handles all three possible cases:
- If the middle name exists and is not an empty string, then it
$0["middleName"]?.isEmpty
evaluates as thefalse
predicate returnstrue
. - If a middle name and an empty string exist, then it
$0["middleName"]?.isEmpty
is evaluated astrue
and the predicate returnsfalse
. - If the middle name does not exist, then it
$0["middleName"]?.isEmpty
evaluates asnil
and the predicate returnsfalse
(becausenil
! =false
).
source to share