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.

+3


source to share


4 answers


This did the trick



names.filter {
  if let middleName = $0["middleName"] {
    return !middleName.isEmpty
  }
  return false
}

      

+4


source


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

.

+2


source


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 the false

    predicate returns true

    .
  • If a middle name and an empty string exist, then it $0["middleName"]?.isEmpty

    is evaluated as true

    and the predicate returns false

    .
  • If the middle name does not exist, then it $0["middleName"]?.isEmpty

    evaluates as nil

    and the predicate returns false

    (because nil

    ! = false

    ).
+1


source


This also works great

names.filter {

if let middleName = $0["middleName"] {
 return middleName != ""
}
return false
}

      

0


source







All Articles