gpt4 book ai didi

ios - 在自定义类中初始化日期会导致错误 : "instance member cannot be used on type"

转载 作者:行者123 更新时间:2023-11-30 13:29:14 24 4
gpt4 key购买 nike

我发现了一些其他问题,但没有一个解决方案有效,也许我的情况在某些关键方面有所不同。代码如下:

class ToDoList {

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day , .Month , .Year], fromDate: date)

let dateCreated : Int = components.year*10_000 + components.month*100 + components.day //TD: take YYYYMMDD from NSDate each initialization
...
}

XCode 错误:

"Instance member 'calendar' cannot be used on type 'ToDoList'.

我尝试将组件实现为带有 getter 的变量,但没有成功。

谢谢!

最佳答案

您不能根据其他实例变量的值在类的顶层声明属性或实例变量。

您可以使用计算属性

class ToDoList {

var dateCreated : Int {
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day , .Month , .Year], fromDate: date)
return components.year * 10_000 + components.month * 100 + components.day
}

}

或者惰性实例化变量

class ToDoList {

lazy var dateCreated : Int = {
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = components([.Day , .Month , .Year], fromDate: date)
return components.year * 10_000 + components.month * 100 + components.day
}()

}

关于ios - 在自定义类中初始化日期会导致错误 : "instance member cannot be used on type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36766668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com