Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3: Date vs NSDate?

Tags:

swift

nsdate

What is the difference between the NS and non NS classes? Particularly NSDate vs Date? Does NS represent some type of wrapper around the core non NS functionality?

like image 501
Marcus Leon Avatar asked Oct 01 '16 20:10

Marcus Leon


People also ask

What is NSDate?

The NSDate class provides methods for comparing dates, calculating the time interval between two dates, and creating a new date from a time interval relative to another date.

How do I get the current date in Objective C?

dateFormat = @"MMMM dd, yyyy"; NSString* dateString = [formatter stringFromDate:date]; Convert a String to a Date: NSDateFormatter* formatter = [[NSDateFormatter alloc]init];


2 Answers

Swift 3 introduced some new overlay value types for existing Foundation class types, such as Date for NSDate, Data for NSData and some more. The full list and details can be found in

  • SE-0069 Mutability and Foundation Value Types

Some of the reasons were

  • Provide proper value semantics,
  • let and var instead of mutable and immutable variants,
  • more "Swifty" APIs.

The new overlay types should provide all functionality that the corresponding Foundation type has, but if necessary, you can always cast from one type to the other.

When existing Foundation APIs are imported into Swift, the types are bridged automatically.

With respect to Date and NSDate: Date is a value type and can be a constant or variable:

var date = Date() date += 10.0 // Add 10 seconds 

whereas NSDate is a reference type and immutable. Also Date is Comparable

let date1 = Date() let date2 = Date()  if date1 < date2 { } 

whereas NSDates can only be compared with .compare().

Remark: For these "overlay types", the value type (struct) such as Date and its Foundation counterpart (class) such as NSDate are different types and both can be used from Swift. It must not be confused with

  • SE-0086 Drop NS Prefix in Swift Foundation

where the NS prefix has simply been dropped for certain Foundation classes, e.g. NSBundle is renamed to Bundle for Swift 3.

like image 87
Martin R Avatar answered Oct 04 '22 00:10

Martin R


NS classes are Objective-C classes. As Objective-C is the older programming language for iOS or MacOS applications, Swift allows you to use those classes structs in your code. So you can migrate applications from Objective-C to Swift if you want to.

The non-NS classes or structs are the Swift equivalents of the the NS classes or structs. You can read more about this issue here or here.

But be aware: As Objective-C and Swift do are different programming languages, it can happen that NS and non-NS classes are not completely working the same way.

like image 22
mbachm Avatar answered Oct 03 '22 23:10

mbachm