Calendar.components 不能与 Swift 中的数组文字一起使用 3
Calendar.components cannot be used with an array literal in Swift 3
我正在尝试构建 class 的蓝图以显示当前日期,即 "Saturday January 14, 2017",但我无法在 [=19] 中创建日历组件数组=] 3. 我是否需要像我在下一年所做的那样将它们分解成单独的变量,然后将每个变量组合成一个字符串?
这是我到目前为止无法编译但通过阅读其他人的代码它在过去有效的代码:
import Foundation
class CurrentCalendarDate {
var currentDateString: String {
get{
let date = Date()
let calendar = Calendar.current
//let components = calendar.component(.year, from: date)
let componetsThatWeWant = calendar.component([.year, .day, .month], from: date)
let readableDate: String = "Today's date is: \(componetsThatWeWant.day) \(componetsThatWeWant.month), \(componetsThatWeWant.year)"
return readableDate
}
}
}
也许您可能需要使用 dateComponents(_:from:)
而不是 component(_:from:)
:
let componetsThatWeWant = calendar.dateComponents([.year, .day, .month], from: date)
但使用 DateFormatter
似乎是更好的选择。
我正在尝试构建 class 的蓝图以显示当前日期,即 "Saturday January 14, 2017",但我无法在 [=19] 中创建日历组件数组=] 3. 我是否需要像我在下一年所做的那样将它们分解成单独的变量,然后将每个变量组合成一个字符串?
这是我到目前为止无法编译但通过阅读其他人的代码它在过去有效的代码:
import Foundation
class CurrentCalendarDate {
var currentDateString: String {
get{
let date = Date()
let calendar = Calendar.current
//let components = calendar.component(.year, from: date)
let componetsThatWeWant = calendar.component([.year, .day, .month], from: date)
let readableDate: String = "Today's date is: \(componetsThatWeWant.day) \(componetsThatWeWant.month), \(componetsThatWeWant.year)"
return readableDate
}
}
}
也许您可能需要使用 dateComponents(_:from:)
而不是 component(_:from:)
:
let componetsThatWeWant = calendar.dateComponents([.year, .day, .month], from: date)
但使用 DateFormatter
似乎是更好的选择。