6

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?

jscs
  • 63,694
  • 13
  • 151
  • 195
Jevon Cowell
  • 411
  • 1
  • 3
  • 13
  • 2
    If you are using Swift, you should use `URLRequest` as it was made using the Swift API Design Guidelines. Most Swift APIs use `URLRequest` now, so if you use `NSURLRequest` you'll have to typecast to `URLRequest` – Tristan Beaton Jun 27 '17 at 00:56

2 Answers2

9

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.

Jason Lemrond
  • 407
  • 2
  • 7
1

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.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117