Reputation: 10978
How should this be done in Swift? The compiler error is "Cannot invoke '==' with an argument list of type '(NSURL, NilLiteralConvertible)'"
var request = NSURLRequest()
if request.URL == nil {
}
It seems like the normal pattern is to declare types optional when an object may not have a value.
However in this case I'm not sure why Apple did not declare the URL property as an optional var within the NSURLRequest class.
Upvotes: 0
Views: 2637
Reputation: 926
Good question. Fortunately, request.URL.absoluteString is an optional. I think this will do what you need:
if (request.URL.absoluteString == nil) { ... }
Or, since NSMutableURLRequest uses an optional when URL is fetched, another option is to use NSMutableURLRequest() instead, if that works for your use case.
var request = NSMutableURLRequest()
if (request.URL == nil) { ... }
Upvotes: 1
Reputation: 90127
You don't. URL
is a non-optional, read only variable of NSURLRequest
.
If you stay in swift there is no way that this parameter can be nil. Unless you use the NSURLRequest()
initializer, which is pretty pointless because URL is read-only and you can't set it.
Use one of the designated initializers. Or use NSMutableURLRequest
, which has a URL
variable that is not read-only and an optional.
Upvotes: 1
Reputation: 299623
Because this would be a pain in the normal (and only meaningful) use case. The normal use case is to call the designated initializer (initWithURL:
), or something that calls the designated initializer with a real URL. So in all normal code, you'd have to unload the NSURL?
every single time. That would get old fast for nothing.
If this were a from-scratch Swift object, then it would have no public init()
, but you can't remove that because it's legal (though meaningless) ObjC. (Well, maybe they can remove it; that may be worth a radar to mark its init()
private.)
So this is a compromise with ObjC-as-typically-programmed vs ObjC-as-legal-syntax. Many of the weirdnesses around calling Cocoa from Swift boil down to this.
If ObjC dev used [[NSURLRequest alloc] init]
as a common pattern, then URL
certainly would have been an optional. ObjC devs pretty much never do this, so it isn't.
As a note, if you're finding yourself in a case where NSURLRequest()
seems useful, the really right answer is almost certainly to use an NSURLRequest?
instead.
Upvotes: 3