ios - Calendar.components 不能与 Swift 3 中的数组文字一起使用

标签 ios swift swift3 nsdate

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

相关文章:

ios - 更新现有的 'Contacts' 电话号码?

ios - 滑动页面 View Controller 时,段 Controller 的选定段应该更改

ios - firebase 忘记密码用法

ios - 如何在 Swift 上将 HTML 代码加载到 WebView

ios - 在 iOS8 中的 App 和 Extension 之间共享核心数据堆栈和数据

ios - 如何从排行榜获取玩家总数

ios - 取消分配导航 Controller 中引用自身的 View Controller

ios - 在 swift 3 中使用 PKHUD 创建自定义 View

ios - 无法将 AudioQueueRef inout 参数传递给 Swift 中的 AudioQueueNewOutput

ios - 键入时搜索大型 Core-Data 数据集