URL.init?(string:String)不应该返回'nil'

时间:2019-10-08 23:01:40

标签: swift

我遇到了Foundation结构URL的字符串初始化程序问题。我将从下面的repl中发布一些代码:

Welcome to Apple Swift version 5.1 (swiftlang-1100.0.270.13 clang-1100.0.33.7).
Type :help for assistance.
  1> import Foundation
  2> let testString = "https://www.apple.com"
testString: String = "https://www.apple.com"
  3> let testUrl1 = URL(string: testString)
testUrl1: URL? = nil
  4> let testUrl2 = URL(string: "https://www.apple.com")
testUrl2: URL? = nil

我想不出为什么会发生这种情况,如果您查看位于https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/URL.swift#L495的初始化程序的源代码,则会在文档中看到以下内容:

/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).

据我所知,我正在测试的字符串是一个有效的URL,并且初始化程序不应返回nil。我已经在两台不同的Mac和全新安装的虚拟机上进行了尝试,并且在所有虚拟机上都得到了相同的结果。 macOS 10.15,Xcode 11.1任何人都对什么地方可能出了错有什么见识?

1 个答案:

答案 0 :(得分:2)

这似乎是REPL问题,也存在于11.0中。但是如果您print(testUrl1),您会看到它确实已设置。