我有一个
struct
需要执行一致的日期格式,所以我希望我的结构有一个 ISO8601DateFormatter
和 .formatOptions = .withFullDate
。
如果我在
struct
实例上有一个常量,那么在 .formatOptions = .withFullDate
中设置 init()
就很容易了。
struct MyStruct1 {
let dateFormatter = ISO8601DateFormatter()
init() {
dateFormatter.formatOptions = .withFullDate
}
// Other functions go here
}
但是如果我有一个静态常量,那么在
.formatOptions = .withFullDate
中设置 init()
是错误的,因为如果我在静态函数中使用常量,它就不会被设置。
我试过这个:
struct MyStruct2 {
static let dateFormatter =
ISO8601DateFormatter(
formatOptions: .withFullDate
)
// Other functions go here
}
但这不能编译。我明白了
Argument passed to call that takes no arguments
。
我错过了什么吗?有没有办法用
ISO8601DateFormatter
获得静态 formatOptions=.withFullDate
?
您可以使用以下初始化语法来设置日期格式化程序(或任何属性):
struct MyStruct2 {
static let dateFormatter: ISO8601DateFormatter = {
var res = ISO8601DateFormatter()
res.formatOptions = .withFullDate
return res
}()
}
如果该属性可能暂时不会使用,并且您希望将其初始化推迟到需要时,请将其从
static let
更改为 static lazy var
。