我希望这会返回一个 Date
对象,表示从现在开始一小时后的时间:
Calendar.current.date(byAdding: DateComponents(hour: 1), to: Date())
但是它返回 nil
。这似乎是对 API 的一种相当直接的使用,所以也许我对这个 API 应该如何工作有一些基本的误解?
这仅似乎会影响 Xcode 中包含的 swift
命令行 REPL(macOS Catalina 10.15.3 上的版本 11.3.1)。
有趣的是,将上述代码包装在 print()
调用中会强制它打印正确的结果。那么为什么它显示nil
呢?
Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15)
Target: x86_64-apple-darwin19.3.0
最佳答案
这是 Swift REPL 中的一个错误,请参阅
- SR-11593 REPL incorrectly reports URL as nil
- SR-12172 Description of Date? expression is printed as nil even when non-nil
它会影响某些 Swift 覆盖类型(例如 Date
、Calendar
、URL
)的可选值和非可选值。示例:
$ swift Welcome to Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15). Type :help for assistance. 1> import Foundation 2> 3> let d1 = Date() d1: Date = {} 4> let d2: Date? = Date() d2: Date? = nil 5> let url = URL(string: "https://www.google.com") url: URL? = nil
作为解决方法,您可以打印这些值:
7> print(d1) 2020-03-03 10:17:00 +0000 8> print(d2) Optional(2020-03-03 10:17:07 +0000) 9> print(url) Optional(https://www.google.com)
关于Swift日期(通过添加:to:) returns nil for trivial calculation in REPL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60459151/