英文:
How to preserve square brackets while creating an URL in Swift?
问题
如何创建URL对象,但保留方括号而不将其转换为%5B和%5D。 谢谢!
英文:
I have let urlString = "https://example.com/[path]/file.txt"
.
How to create URL object, but preserve square brackets and not converting it to %5B and %5D.
Thank you!
答案1
得分: 1
TL;DR: 根据设计,您不能这样做。这不是有效的URL,因此无法用 URL
表达。
Long version:
URI(包括URL)的路径部分由RFC 3986 Section 3.3定义。每个段(在 /
之间)中允许的字符称为 pchar
,定义如下:
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
[
和 ]
不在此列表中,因此不能出现在路径中。您必须进行百分比编码。
您可以创建包括这些字符的字符串,但它不能是URL。
英文:
TL;DR: You can't, by design. That isn't a valid URL, so it can't be expressed with URL
.
Long version:
The path component of a URI (including URLs) is defined by RFC 3986 Section 3.3. The allowed characters in each segment (between /
) are called pchar
, defined as follows:
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
[
and ]
are not on that list, and so cannot be in the path. You must percent-encode them.
You are free to create a String that includes those characters, but it cannot be an URL.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论