数组中的Swift表达式,空或不存在的字典 - 可靠地为零?

时间:2017-01-17 21:36:30

标签: swift swift3 optional-variables

数组的字典词典

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")
}

我是否正确?

2 个答案:

答案 0 :(得分:3)

您是对的,但您可能会发现删除可选的之前

更容易
(blah["foo"] ?? []).count 

if let array = blah.down["foo"], !array.isEmpty {
   print("some foos exist!!")
} else {
   print("there are profoundly no foos")
}

答案 1 :(得分:1)

是。但我可能会用可选的绑定来编写它,例如:

$(function() {
   var currentPage = window.location.pathname.split('/').pop();
   $('.NavBar ul li a[href*="'+currentPage+'"]').css({
      borderTop: "4px solid #01A2A6",
      color: "#01A2A6"
   });
});