【问题标题】:Calendar.components cannot be used with an array literal in Swift 3Calendar.components 不能与 Swift 3 中的数组文字一起使用
【发布时间】:2017-01-15 04:02:45
【问题描述】:

我正在尝试构建一个类的蓝图,以便将当前日期显示为“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

        }
    }
}

【问题讨论】:

  • var currentDateString: Int { 返回一个 Int ???没有意义
  • 你应该使用 DateFormatter。 formatter.dateStyle = .full
  • 您可以将其作为参考,并使其完整而不是简短。 stackoverflow.com/a/28347285/2303865

标签: ios swift swift3 nsdate


【解决方案1】:

也许您可能需要使用dateComponents(_:from:) 而不是component(_:from:)

let componetsThatWeWant = calendar.dateComponents([.year, .day, .month], from: date)

但使用DateFormatter 似乎是更好的选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多