What is the difference between NSURLRequest and URLRequest in Swift?
Asked Answered
A

2

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?

Artifice answered 27/6, 2017 at 0:46 Comment(1)
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 URLRequestTelpher
W
10

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.

Woo answered 27/6, 2017 at 1:32 Comment(1)
You can see the source of URLRequest here: github.com/apple/swift/blob/master/stdlib/public/Darwin/…Salba
N
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.

Neysa answered 27/6, 2017 at 1:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.