Swift日期(byAdding:to :)返回nil以进行REPL中的琐碎计算 [英] Swift date(byAdding:to:) returns nil for trivial calculation in REPL

查看:101
本文介绍了Swift日期(byAdding:to :)返回nil以进行REPL中的琐碎计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望它返回一个 Date 对象,该对象表示从现在开始一小时的时间:

I expect this to return a Date object representing the time one hour from now:

Calendar.current.date(byAdding: DateComponents(hour: 1), to: Date()) 

但是它返回 nil 。这似乎是API的一种非常直接的用法,所以也许我对API的工作方式有一些基本的误解?

However it returns nil. This seems like a rather straightforward use of the API so perhaps I have some fundamental misconception about how this API should work?

影响Xcode随附的 swift 命令行REPL(在macOS Catalina 10.15.3上的版本11.3.1)。

This only appears to affect the swift command line REPL included with Xcode (version 11.3.1 on macOS Catalina 10.15.3).

有趣的是,将上述代码包装在 print()调用中会强制其打印正确的结果。那么为什么显示 nil

Interestingly, wrapping the above code in a print() call forces it to print the correct result. So why is it showing 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,请参见

This is a bug in the Swift REPL, see

  • SR-11593 REPL incorrectly reports URL as nil
  • SR-12172 Description of Date? expression is printed as nil even when non-nil

它会影响某些Swift覆盖的可选值和非可选值类型(例如日期日历 URL )。示例:

It affects both optional and non-optional values of some Swift overlay types (such as Date, Calendar, URL). Example:


$ 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

作为解决方法,您可以打印值:

As a workaround you can print the values:


  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日期(byAdding:to :)返回nil以进行REPL中的琐碎计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆