[英]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: 您还可以使用nil-coalescing运算符来非常简洁地表达它:
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). 这将使用空字符串替换缺少的中间名,因此您可以使用
.isEmpty
处理(如果要获取具有中间名称的那些,则可以取消)。
You can also use optional chaining and the nil-coalescing operator to express it another way: 您还可以使用可选链接和nil-coalescing运算符以另一种方式表达它:
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
). $0["middleName"]?.isEmpty
如果值不是nil
则调用isEmpty
,但返回一个可选项(因为它可能是nil
)。 You then use ??
然后你用
??
to substitute true
for nil
. 替换
nil
true
。
Slightly shorter: 略短:
let result = names.filter { $0["middleName"]?.isEmpty == false }
This handles all three possible cases: 这处理所有三种可能的情况:
$0["middleName"]?.isEmpty
evaluates to false
and the predicate returns true
. $0["middleName"]?.isEmpty
求值为false
,谓词返回true
。 $0["middleName"]?.isEmpty
evaluates to true
and the predicate returns false
. $0["middleName"]?.isEmpty
计算结果为true
,谓词返回false
。 $0["middleName"]?.isEmpty
evaluates to nil
and the predicate returns false
(because nil
!= false
). $0["middleName"]?.isEmpty
求值为nil
,谓词返回false
(因为nil
!= false
)。 This also works fine 这也很好
names.filter {
if let middleName = $0["middleName"] {
return middleName != ""
}
return false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.