我遇到了 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。任何人都知道什么可能是错的?
最佳答案
这似乎是一个 REPL 问题并且也存在于 11.0 中。但是,如果您 print(testUrl1)
,您会发现它确实已设置。
关于swift - URL.init?(字符串 : String) returns 'nil' when it shouldn't,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58295020/