简体   繁体   中英

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.

This did the trick

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

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 .

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

This also works fine

names.filter {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM