Swift错误:不允许在顶层使用语句 [英] Swift Error: Statements are not allowed at the top level

查看:387
本文介绍了Swift错误:不允许在顶层使用语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历Argo文档中的Swift JSON解析( https://github.com/thoughtbot/Argo ),并且它们提供了应检索JSON数据的简单代码段,但运行时出现错误.该代码段是:

I'm going through the Argo documentation for Swift JSON Parsing (https://github.com/thoughtbot/Argo) and they provide a simple code snippet that should retrieve the JSON data, but I get an error when running it. The snippet is:

// Wherever you receive JSON data:

let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil)

if let j: AnyObject = json {
  let user: User? = decode(j)
}

我得到的错误是不允许在顶层发表声明",该行表示是否让j ...

and the error I get is "Statements are not allowed at the top level", on the line that says if let j...

为什么这会导致错误?为什么在github自述文件中如果它不起作用呢?

Why would this cause an error and why is this in their github readme if it doesn't work?

推荐答案

因为它是一个代码段.您应该在合法的函数内使用它.可执行代码只能出现在函数中.

Because it is a snippet. You are expected to use it inside a function, where it is legal. Executable code can appear only in a function.

这篇关于Swift错误:不允许在顶层使用语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆