swift - URL.init?(字符串 : String) returns 'nil' when it shouldn't

标签 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。任何人都知道什么可能是错的?

最佳答案

这似乎是一个 REPL 问题并且也存在于 11.0 中。但是,如果您 print(testUrl1),您会发现它确实已设置。

关于swift - URL.init?(字符串 : String) returns 'nil' when it shouldn't,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58295020/

相关文章:

ios - 从后台激活时,Firebase 应用程序在启动时崩溃

ios - 按下一个按钮,并使相同的按钮出现在同一页面上

swift - 在智能相册 iOS 13 中找不到相机胶卷相册

ios - 如何固定 UIPageControl 的位置?使用 PageViewController 更改页面时始终将其修复在顶部?

ios - UITextField 不响应点击

ios - UITableViewCell 的 ViewDidDisappear

ios - UIPickerView 行为异常

xcode - touchesbegan/moved/ended 不适用于 xcode 6.3

ios - Firebase 重置密码 IOS 应用 xcode

ios - Swift 在 MFMailComposeViewController didFinishWith 结果中显示警报