Nassif
Nassif

Reputation: 1223

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.

Upvotes: 3

Views: 6815

Answers (4)

Martin R
Martin R

Reputation: 539965

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).

Upvotes: 4

Nassif
Nassif

Reputation: 1223

This did the trick

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

Upvotes: 6

Airspeed Velocity
Airspeed Velocity

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

Nassif
Nassif

Reputation: 1223

This also works fine

names.filter {

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

Upvotes: 1

Related Questions