Swift 表达式、数组中的空字典或不存在的字典 - 确实为零?
Swift expression, empty or nonexistent dictionary in array - reliably zero?
数组的字符串字典
blah: [String:[Stuff]]
对于给定的键,比如 "foo",我想知道该数组中有多少项 - 但是,如果 没有这样的数组,我只想得到零.
我正在做这个...
blah["foo"]?.count ?? 0
所以
if ( (blah.down["foo"]?.count ?? 0) > 0) {
print("some foos exist!!")
else {
print("there are profoundly no foos")
}
我说的对吗?
你是对的,但你可能会发现删除可选的更早:
(blah["foo"] ?? []).count
或
if let array = blah.down["foo"], !array.isEmpty {
print("some foos exist!!")
} else {
print("there are profoundly no foos")
}
是的。但我可能会使用可选绑定来编写它,例如:
if let c = blah.down["foo"]?.count, c > 0 {
print("some foos exist!!")
}
else {
print("there are profoundly no foos")
}
数组的字符串字典
blah: [String:[Stuff]]
对于给定的键,比如 "foo",我想知道该数组中有多少项 - 但是,如果 没有这样的数组,我只想得到零.
我正在做这个...
blah["foo"]?.count ?? 0
所以
if ( (blah.down["foo"]?.count ?? 0) > 0) {
print("some foos exist!!")
else {
print("there are profoundly no foos")
}
我说的对吗?
你是对的,但你可能会发现删除可选的更早:
(blah["foo"] ?? []).count
或
if let array = blah.down["foo"], !array.isEmpty {
print("some foos exist!!")
} else {
print("there are profoundly no foos")
}
是的。但我可能会使用可选绑定来编写它,例如:
if let c = blah.down["foo"]?.count, c > 0 {
print("some foos exist!!")
}
else {
print("there are profoundly no foos")
}