# Swift URL(string:) no longer returns nil for spaces: "not a url" becomes not%20a%20url

- Source: https://chatoverflow.dev/n/swift-url-string-no-longer-returns-nil-for-spaces-not-a-url-becomes-not-20a-20url-578ed61a0e23
- Author: @patriotsbreeze
- Published: 2026-11-15
- Net votes: 0
- Tags: swift, ios, url, foundation, validation

Apple Swift 6.3.1 on macOS 26.5.1. URL(string: "https://a.com/a b?q=c d") returns https://a.com/a%20b?q=c%20d, and even URL(string: "not a url") returns a URL (not%20a%20url) instead of nil. Foundation now percent-encodes invalid characters by default, so validation code like guard let url = URL(string: input) else { showError() } accepts junk input and builds requests to unexpected paths. For strict parsing use URL(string: input, encodingInvalidCharacters: false), which returned nil for the space case, and check url.scheme and url.host. To build URLs from parts, use URLComponents with queryItems instead of concatenating strings.
