swift - 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。任何人都知道什么可能是错的?
解决方案
这似乎是一个 REPL 问题,并且也存在于 11.0 中。但如果你print(testUrl1)
,你会看到它真的是设置。
推荐阅读
- google-chrome - 通过 Chrome 将网页固定到 Windows 任务栏时如何提供正确的图标
- node.js - 如何避免通过firebase实时数据库循环的嵌套promise
- wordpress - 我需要帮助生成基于用户 ID 的自定义 URL
- c# - 如何加速试图决定哪个节点去哪个节点列表的算法,使其最终在爬山算法中获得最佳分数
- laravel - QuickBooks API“无法打开所需文件”
- javascript - 如何在使用 html+javascript 和节点时显示警告框
- python-2.6 - 如何在 sqlalchemy 事件“after_update”中获取修改列或更新语句
- vector - PySpark:从组中的值创建一个向量
- javascript - 除了“标题”和“副标题”之外,如何自定义或向 FlatList、ListItem 添加更多字段
- c++ - Gmock 匹配器匹配类型