Xcode "Expected Delcaration","Expression not allowed at the top level"错误

标签 xcode swift

当我收到“Expected Declaration”错误并且“Instance member”something”不能用于类型“viewcontroller”时,我试图在 viewcontroller.swift 文件中实现一个 NSDatecomponent enter image description here

所以,我决定制作一个新的 .swift 文件,然后在那里实现 NSDatecomponents。但是后来我得到了“顶层不允许使用表达式”错误。 enter image description here

根据我在谷歌上的发现,我知道我应该在一个函数中实现它,但我不知道我应该把它包装成什么样的函数。我也想知道为什么我在 viewcontroller.swift 文件中得到错误以供将来引用。提前谢谢你,如果我的问题重复,我很抱歉。

这是原始代码

let weekBMondayComponents:NSDateComponents = NSDateComponents()
weekBMondayComponents.year = 2016
weekBMondayComponents.month = 01
weekBMondayComponents.day = 11
weekBMondayComponents.hour = 08
weekBMondayComponents.minute = 39
weekBMondayComponents.timeZone = NSTimeZone.systemTimeZone()
let weekBMonday = userCalendar.dateFromComponents(weekBMondayComponents)!

最佳答案

您需要将 weekBMondayComponents 声明为子类的属性或变量,并可能在 viewDidLoad 通知处理程序中对其进行初始化。

class ViewController: UIViewController {
    var weekBMondayComponents:NSDateComponents = NSDateComponents()

func setUpADay() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    weekBMondayComponents.year = 2016
    weekBMondayComponents.month = 01
    weekBMondayComponents.day = 11
    weekBMondayComponents.hour = 08
    weekBMondayComponents.minute = 39
    weekBMondayComponents.timeZone = NSTimeZone.systemTimeZone()
}

关于Xcode "Expected Delcaration","Expression not allowed at the top level"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34625484/

相关文章:

swift - 背景清晰的 NSProgressIndicator

基于 iOS ADMOB 奖励的视频广告加载失败

ios - Storyboard中的 UITabBarController 自定义类不起作用

swift - 登录成功后切换到另一个屏幕

xcode - UITextViewDelegate 函数应该在 Xcode 8.0 中与 URL 交互

swift - 检查日期是否介于 2 个日期之间

ios - Xcode 在 SWIFT 中跳过了我在 autoreleasepool 中的整个代码

ios - Swift 应用程序在打开后退出,在 Xcode 中运行

ios - 火力地堡 REST API

Swift 4,同时访问元组成员作为 inout