3

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.

4 Answers 4

6

This did the trick

names.filter {
  if let middleName = $0["middleName"] {
    return !middleName.isEmpty
  }
  return false
}
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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.

Comments

1

This also works fine

names.filter {

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

1 Comment

the others are more succinct, but this is more readable for those not familiar with closure syntax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.