Xcode"预期的贬值","表达不允许在顶级"错误

时间:2016-01-06 04:09:21

标签: xcode swift

当我得到"预期声明"我试图在viewcontroller.swift文件中实现一个NSDatecomponent。错误和"实例成员"某事"不能用于类型" viewcontroller" enter image description here

所以,然后我决定创建一个新的.swift文件,然后在那里实现NSDatecomponents。但后来我得到了#34;表达式不允许进入顶级"错误。 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)!

1 个答案:

答案 0 :(得分:3)

您希望将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()
}