我正在尝试构建一个类的蓝图,以便将当前日期显示为“2017 年 1 月 14 日星期六”,但我无法在 Swift 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
似乎是一个更好的选择。
关于ios - Calendar.components 不能与 Swift 3 中的数组文字一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41657703/