I'm looking through some swift documents and I see that NSURLRequest and URLRequest are practically the same, with the added tidbit that NSURLRequest is used:
when you need reference semantics or other Foundation-specific behavior.
Is one faster than the other and in what situations should one be used over the other?
NSMutableURLRequest is a subclass of NSURLRequest that allows you to change the request's properties. NSMutableURLRequest only represents information about the request. Use other classes, such as NSURLSession , to send the request to a server.
An NSURLConnection object lets you load the contents of a URL by providing a URL request object. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request. You perform most of your configuration on the URL request object itself. Note.
URLRequest
is an overlay for NSURLRequest
so you are correct in thinking that they are essentially the same thing. They are different classes but they are intended to provide the same functionality. The NS version is more of a legacy API that was a holdover from Objective-C and the non-NS version is the 'swifty' one.
Here is a quote from apple's own documentation on NSURLRequest:
The Swift overlay to the Foundation framework provides the URLRequest structure, which bridges to the NSURLRequest class and its mutable > subclass, NSMutableURLRequest. For more information about value types, see Working with Cocoa Frameworks in Using Swift with Cocoa and Objective-C (Swift 4).
Additionally, here is the actual swift proposal from when they decided to drop NS from a number of classes with Foundation.
https://github.com/apple/swift-evolution/blob/master/proposals/0086-drop-foundation-ns.md
Essentially, if you are using Objective-C you use the NS versions. If you are using Swift you want to default to using the Non-NS versions and only use the NS version when you are trying to bridge to Objective-C or a specific library is requiring you to use the NS version.
Swift has a certain pattern in Foundation of wrapping some NS classes with Swift constructs. Examples of this include String (NSString), Array (NSArray), JSONSerialization (NSJSONSerialization), Date (NSDate), …
Use the wrapper whenever possible dropping down to the NS version only when needed. In this case, use URLRequest unless you run into problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With