Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an array based on empty value in Swift

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.

like image 381
Nassif Avatar asked Jun 28 '26 12:06

Nassif


2 Answers

This did the trick

names.filter {
  if let middleName = $0["middleName"] {
    return !middleName.isEmpty
  }
  return false
}
like image 128
Nassif Avatar answered Jun 30 '26 13:06

Nassif


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 $0["middleName"]?.isEmpty evaluates to false and the predicate returns true.
  • If the middle name exists and is empty string, then $0["middleName"]?.isEmpty evaluates to true and the predicate returns false.
  • If the middle name does not exist, then $0["middleName"]?.isEmpty evaluates to nil and the predicate returns false (because nil != false).
like image 33
Martin R Avatar answered Jun 30 '26 13:06

Martin R