【问题标题】:Xcode "Expected Delcaration","Expression not allowed at the top level" errorXcode "Expected Delcaration","Expression not allowed at the top level" 错误
【发布时间】:2016-01-06 04:09:20
【问题描述】:

我试图在 viewcontroller.swift 文件中实现 NSDatecomponent,但出现“预期声明”错误,并且“实例成员”某物不能用于“viewcontroller”类型

所以,我决定创建一个新的 .swift 文件,然后在那里实现 NSDatecomponents。但后来我得到了“顶级表达式不允许”错误。

根据我在谷歌上搜索的结果,我知道我应该在一个函数中实现它,但我不知道我应该把它包装成什么样的函数。我还想知道为什么我在 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)!

【问题讨论】:

  • 你的用户日历是什么? NSC 日历?
  • @Charles-olivierDemers,对不起,忘了说我在顶部有这个代码let userCalendar = NSCalendar.currentCalendar()

标签: xcode swift


【解决方案1】:

您需要将 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()
}

【讨论】:

    猜你喜欢
    • 2021-08-30
    • 2021-12-01
    • 1970-01-01
    • 2018-08-21
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    相关资源
    最近更新 更多