Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

Swift 3: Date vs 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?

question from:https://stackoverflow.com/questions/39811352/swift-3-date-vs-nsdate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...