ios - 来自 Apple 网站的日期示例代码不起作用?

标签 ios swift swift3

我想弄清楚如何在 Swift 3 中使用当前日期。我读到 Swift 已将 NSDate 移动到 Date 对象。所以我检查了this示例代码:

let dateFormatter = DateFormatter()
let date = Date(timeIntervalSinceReferenceDate: 410220000)

// US English Locale (en_US)
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMd") // set template after setting locale
print(dateFormatter.string(from: date)) // December 31

// British English Locale (en_GB)
dateFormatter.locale = Locale(identifier: "en_GB")
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMd") // // set template after setting locale
print(dateFormatter.string(from: date)) // 31 December

但是当我将其复制并粘贴到我的 Xcode 时,它​​显示错误

Use of unresolved identifier DateFormatter
Use of unresolved identifier Date

当我从终端检查我的 swift 版本时:

xcrun swift -version
Apple Swift version 3.0.1 (swiftlang-800.0.58.6 clang-800.0.42.1)
Target: x86_64-apple-macosx10.9

我是否缺少导入某些库?

编辑

如果我改成这样

let dateFormatter = NSDateFormatter()
let date = NSDate(timeIntervalSinceReferenceDate: 410220000)

它工作正常。

最佳答案

当您在终端中检查它时,您的计算机上可能安装了最新的 Swift 版本,但您的项目必须在 Swift 2.3 上运行。

Swift 2.3 不识别DateFormatterDate 类型,它仅在 Swift 3.0+ 中引入。

关于ios - 来自 Apple 网站的日期示例代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41288672/

相关文章:

ios - Swift 同时将对象转换为类型和协议(protocol)

iOS UITableViewWrapperView 在带有 Xcode9 的 iOS 11 中不存在

ios - 编程约束折叠单元格 View

ios - 正在寻找用响应式(Reactive) cocoa 链接网络请求的依赖树的最优雅的方法?

swift - 有人可以告诉我 { _ in nil } 在这段 Swift 代码中做了什么

swift 如何防止图像旋转和淀粉

ios - shouldInteractWith url textview 委托(delegate)未在 ios9 中调用但在 ios10 中工作?

ios - 在 viewDidLoad block UI 中对图像使用 GaussianBlur

ios - 如何在 Google 云端硬盘上保存和检索图像

ios - 自定义 TableViewCell 的 UIimageView 宽度为单元格宽度的 1/3,单元格高度 = 图像纵横比