I have just discovered following behaviour of NSURLComponents and I'm looking for confirmation if it is in fact a bug.
var components = NSURLComponents(string: "apple.com")!
components.scheme = "http"
print(components.scheme) // prints "Optional("http")\n"
print(components.URL?.absoluteURL) // prints ""Optional(http:apple.com)\n", I'd expect http://apple.com
When trying to set scheme as "http://" I get an error which is in line with what documentation says. So it seems there is no way of setting the scheme after URLComponents initialisation and getting correct URL as a result.
I have just discovered following behaviour of NSURLComponents and I'm looking for confirmation if it is in fact a bug.
Unless you’re using Swift on Linux plus the in-development Foundation framework, NSURLComponents is part of a system framework, not part of Swift.
var components = NSURLComponents(string: "apple.com")!
That’s incorrect, and I’m surprised the method didn’t fail, since “apple.com” is not a valid URL. Try initializing an empty object and then setting its host to “apple.com”.
—Jens
···
On May 25, 2016, at 1:56 PM, Michal Kalinowski via swift-users <swift-users@swift.org> wrote:
var components = NSURLComponents(string: "apple.com")!
That’s incorrect, and I’m surprised the method didn’t fail, since “apple.com” is not a valid URL. Try initializing an empty object and then setting its host to “apple.com”.
"apple.com" is a perfectly valid relative URL, and that's how NSURLComponents interpreted it:
1> import Foundation
2> let comps = NSURLComponents(string: "apple.com")!
3> comps.description
$R1: String = "<NSURLComponents 0x100707670> {scheme = (null), user = (null), password = (null), host = (null), port = (null), path = apple.com, query = (null), fragment = (null)}"
Note that `host` is nil, but `path` is "apple.com".
Your suggestion to initialize an empty `NSURLComponents` and set the `host` field is a good one, however.