首页 > 解决方案 > URL.init?(string: String) 在不应该的时候返回 'nil'

问题描述

我遇到了 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。任何人都知道什么可能是错的?

标签: swift

解决方案


这似乎是一个 REPL 问题,并且也存在于 11.0 中。但如果你print(testUrl1),你会看到它真的是设置。


推荐阅读