草庐IT

关于 ios:Swift: If let 语句无法处理空数组

codeneng 2023-03-28 原文

Swift: If let statement failing to handle empty array

我有一个使用 Foursquare API 下载 JSON 数据的应用程序。我正在使用 NSURLSession 和带有完成块方法的 dataTaskWithRequest 来获取数据。我得到的数据很好,但有时名为 groups 的嵌套数组可能为空。当我像下面这样解析 JSON 时,由于某种原因,我的条件语句没有像我期望的那样处理空数组。而不是将数组评估为空并继续执行 if let...else 语句的"else"部分,而是通过运行时错误声明:index 0 beyond bounds of empty array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if let response: NSDictionary = data["response"] as? [String: AnyObject],
            groups: NSArray = response["groups"] as? NSArray,
                        // Error here \\|/ (sometimes groups array is empty)
            dic: NSDictionary = groups[0] as? NSDictionary,
            items: NSArray = dic["items"] as! NSArray {

}

else {

    // Never gets here. Why?
    // IF the groups array is empty, then the if let should return
    // false and drop down to the else block, right?
}

我对 Swift 比较陌生,谁能告诉我为什么会发生这种情况以及我能做些什么来解决这个问题?谢谢

  • 你试过 nsnull 检查数组响应对象的值吗?
  • 意思是实际测试类类型 NSNull?
  • 我知道我可以做这样的事情,我只是想在这里理解 Swift。在我看来,如果它是空的(意思是假的)它会这样评估。当 if 语句通常这样做时,它们会掉到 else 块中。我想我在这里对 Swift 的 if let 有点困惑。
  • 好吧,你可以试试这个,这是来自 Matt(IOS 标签上的顶部海报):或 card:AnyObject in arr { switch card { // 如何测试不同的可能类型 case let card as NSNull: // 做一个thing case let card as Card: // 做不同的事情 default: fatalError("unexpected object in card array") // 永远不会发生! } } stackoverflow.com/questions/24026609/...
  • 我总是 NSNull 检查,但是 vadian,在他的答案下面可能也有你的答案,这与该值为 null 或 vadian 发布的内容有关,它也发生在 Obj C 中,而不仅仅是 swift


如果数组为空,则必须在 if let 语句之外显式检查,因为

空数组永远不是可选的

1
2
3
4
5
6
7
8
9
if let response = data["response"] as? [String: AnyObject], groups = response["groups"] as? NSArray {
  if !groups.isEmpty {
    if let dic = groups[0] as? NSDictionary {
       items = dic["items"] as! NSArray
       // do something with items
       println(items)
    }
  }
} else ...

向下转换类型时可以省略所有类型注释

但是,您可以使用 where 子句执行检查,这适用于 Swift 1.2 和 2

1
2
3
4
5
6
7
if let response = data["response"] as? [String: AnyObject],
                  groups = response["groups"] as? [AnyObject] where !groups.isEmpty,
                  let dic = groups[0] as? NSDictionary,
                  items = dic["items"] as? NSArray {
   // do something with items
   println(items)
} else {...

  • 我认为这是我必须要做的,并且已经这样做了。我只是想凭借 Swift 的强大功能,if let 的预期目的实际上可以解决我的情况。感谢您的回答。


在尝试访问之前确保数组不为空:

1
2
3
4
5
6
7
8
9
10
11
if let response: NSDictionary = data["response"] as? [String: AnyObject],
    let groups: NSArray = response["groups"] as? NSArray where groups.count > 0 {
        if let dic: NSDictionary = groups[0] as? NSDictionary,
            let items: NSArray = dic["items"] as? NSArray {
             // Do something..
             return // When the 2nd if fails, we never hit the else clause
        }
}

// Do logic for else here
...

在语句之间使用 && 运算符。

例如这不会崩溃:

1
2
3
4
5
6
7
var a = 4;
var c = 5;
var array = Array<Int>();

if  a > 2 &&  c > 10 && array[0] != 0 {

}

有关关于 ios:Swift: If let 语句无法处理空数组的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  3. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  4. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  5. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  6. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  7. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  8. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  9. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  10. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

随机推荐