Merge pull request #815 from naithar/NSAffineTransform

diff --git a/CoreFoundation/Base.subproj/CFInternal.h b/CoreFoundation/Base.subproj/CFInternal.h
index 3b60cc2..a716f90 100644
--- a/CoreFoundation/Base.subproj/CFInternal.h
+++ b/CoreFoundation/Base.subproj/CFInternal.h
@@ -104,14 +104,14 @@
 #endif
 #include <pthread.h>
 
-#if __has_include(<os/log.h>)
+#if !DEPLOYMENT_RUNTIME_SWIFT && __has_include(<os/log.h>)
 #import <os/log.h>
 #else
 typedef struct os_log_s *os_log_t;
-#define os_log(...)
-#define os_log_info(...)
-#define os_log_debug(...)
-#define os_log_error(...)
+#define os_log(...) do { } while (0)
+#define os_log_info(...) do { } while (0)
+#define os_log_debug(...) do { } while (0)
+#define os_log_error(...) do { } while (0)
 #define os_log_create(...) (NULL)
 #endif
 
diff --git a/CoreFoundation/Base.subproj/CFUtilities.c b/CoreFoundation/Base.subproj/CFUtilities.c
index 63d4d9e..d536d46 100644
--- a/CoreFoundation/Base.subproj/CFUtilities.c
+++ b/CoreFoundation/Base.subproj/CFUtilities.c
@@ -604,7 +604,7 @@
 
 static bool also_do_stderr(const _cf_logging_style style) {
     bool result = false;
-#if DEPLOYMENT_TARGET_EMBEDDED_MINI
+#if DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX
     // just log to stderr, other logging facilities are out
     result = true;
 #elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
diff --git a/CoreFoundation/Base.subproj/SwiftRuntime/CoreFoundation.h b/CoreFoundation/Base.subproj/SwiftRuntime/CoreFoundation.h
index 99c4d6d..9abb6b9 100644
--- a/CoreFoundation/Base.subproj/SwiftRuntime/CoreFoundation.h
+++ b/CoreFoundation/Base.subproj/SwiftRuntime/CoreFoundation.h
@@ -40,11 +40,11 @@
 #include <time.h>
 
 #if __has_include(<netdb.h>)
-#include <netdb.h> // for NSHost.swift
+#include <netdb.h> // for Host.swift
 #endif
 
 #if __has_include(<ifaddrs.h>)
-#include <ifaddrs.h> // for NSHost.swift
+#include <ifaddrs.h> // for Host.swift
 #endif
 
 #if defined(__STDC_VERSION__) && (199901L <= __STDC_VERSION__)
diff --git a/CoreFoundation/RunLoop.subproj/CFMachPort.c b/CoreFoundation/RunLoop.subproj/CFMachPort.c
index 457cef5..60b61c4 100644
--- a/CoreFoundation/RunLoop.subproj/CFMachPort.c
+++ b/CoreFoundation/RunLoop.subproj/CFMachPort.c
@@ -20,7 +20,6 @@
 #include <stdio.h>
 #include "CFInternal.h"
 #include <os/lock.h>
-#include <os/log.h>
 
 
 // This queue is used for the cancel/event handler for dead name notification.
diff --git a/Docs/GettingStarted.md b/Docs/GettingStarted.md
index 5a6a784..7b65bfd 100644
--- a/Docs/GettingStarted.md
+++ b/Docs/GettingStarted.md
@@ -8,7 +8,7 @@
 
 * The latest version of Xcode
 * The latest version of the OS X SDK (at this time: 10.11)
-* The [current Swift toolchain](https://swift.org/download/#latest-development-snapshots).
+* The [current Swift toolchain](https://swift.org/download/#snapshots).
 
 Foundation is developed at the same time as the rest of Swift, so the most recent version of the compiler is required in order to build it.
 
diff --git a/Docs/Status.md b/Docs/Status.md
index 38400fb..071a49c 100644
--- a/Docs/Status.md
+++ b/Docs/Status.md
@@ -47,7 +47,7 @@
     |------------------------------|-----------------|---------------|--------------------------------------------------------------------------------------------------------------------|
     | `URLAuthenticationChallenge` | Unimplemented   | None          |                                                                                                                    |
     | `URLCache`                   | Unimplemented   | None          |                                                                                                                    |
-    | `URLCredential`              | Mostly Complete | Incomplete    | `NSCopying` remains unimplemented                                                                                  |
+    | `URLCredential`              | Complete | Incomplete    | 									                                                                                  |
     | `URLCredentialStorage`       | Unimplemented   | None          |                                                                                                                    |
     | `NSURLError*`                | Complete        | N/A           |                                                                                                                    |
     | `URLProtectionSpace`         | Unimplemented   | None          |                                                                                                                    |
@@ -57,7 +57,7 @@
     | `NSMutableURLRequest`        | Mostly Complete | Incomplete    |                                                                                                                    |
     | `URLResponse`                | Mostly Complete | Incomplete    |                                                                                                                    |
     | `NSHTTPURLResponse`          | Mostly Complete | Substantial   |                                                                                                                    |
-    | `NSURL`                      | Mostly Complete | Substantial   | `NSCoding` with non-keyed-coding archivers, `checkResourceIsReachable()`, and resource values remain unimplemented |
+    | `NSURL`                      | Mostly Complete | Substantial   | `checkResourceIsReachable()`, and resource values remain unimplemented 											|
     | `NSURLQueryItem`             | Mostly Complete | N/A           |                                                                                                                    |
     | `URLResourceKey`             | Complete        | N/A           |                                                                                                                    |
     | `URLFileResourceType`        | Complete        | N/A           |                                                                                                                    |
@@ -96,12 +96,12 @@
     | `DateComponentFormatter`        | Unimplemented   | None          |                                                                                           |
     | `DateIntervalFormatter`         | Unimplemented   | None          |                                                                                           |
     | `EnergyFormatter`               | Unimplemented   | None          |                                                                                           |
-    | `LengthFormatter`               | Unimplemented   | None          |                                                                                           |
+    | `LengthFormatter`               | Complete 	    | Substantial   |                                                                                           |
     | `MassFormatter`                 | Unimplemented   | None          |                                                                                           |
     | `NumberFormatter`               | Mostly Complete | Substantial   | `objectValue(_:range:)` remains unimplemented                                             |
     | `PersonNameComponentsFormatter` | Unimplemented   | None          |                                                                                           |
     | `ByteCountFormatter`            | Unimplemented   | Incomplete    |                                                                                           |
-    | `DateFormatter`                 | Mostly Complete | Incomplete    | `objectValue(_:range:)` and `setLocalizedDateFormatFromTemplate(_:)` remain unimplemented |
+    | `DateFormatter`                 | Mostly Complete | Incomplete    | `objectValue(_:range:)` remain unimplemented 										 |
     | `Formatter`                     | Complete        | N/A           |                                                                                           |
     | `MeasurementFormatter`          | Unimplemented   | None          |                                                                                           |
 
@@ -122,8 +122,8 @@
 
     | Entity Name                 | Status          | Test Coverage | Notes                                                                         |
     |-----------------------------|-----------------|---------------|-------------------------------------------------------------------------------|
-    | `NSJSONSerialization`       | Mostly Complete | Substantial   | `jsonObject(with:options:)` remains unimplemented                             |
-    | `NSKeyedArchiver`           | Mostly Complete | Substantial   | `init()` and `encodedData` remain unimplemented                               |
+    | `NSJSONSerialization`       | Mostly Complete | Substantial   | `jsonObject(with:options:)` with streams remains unimplemented             |
+    | `NSKeyedArchiver`           | Complete        | Substantial   |                              |
     | `NSKeyedCoderOldStyleArray` | N/A             | N/A           | For internal use only                                                         |
     | `NSKeyedUnarchiver`         | Mostly Complete | Substantial   | `decodingFailurePolicy.set` remains unimplemented                             |
     | `NSKeyedArchiverHelpers`    | N/A             | N/A           | For internal use only                                                         |
@@ -151,7 +151,7 @@
 
     | Entity Name           | Status          | Test Coverage | Notes                                                                                                                                                               |
     |-----------------------|-----------------|---------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-    | `NSOrderedSet`        | Mostly Complete | Substantial   | `NSCoding` with non-keyed-coding archivers, `NS[Mutable]Copying`, and `array` & `set` (and associated indexing methods) remain unimplemented                        |
+    | `NSOrderedSet`        | Mostly Complete | Substantial   | `NS[Mutable]Copying`, and `array` & `set` (and associated indexing methods) remain unimplemented                        |
     | `NSMutableOrderedSet` | Mostly Complete | Substantial   | `NSCoding` and `sortRange(_:options:, usingComparator:)` with non-empty options remain unimplemented                                                                |
     | `NSCFArray`           | N/A             | N/A           | For internal use only                                                                                                                                               |
     | `NSIndexSet`          | Mostly Complete | Incomplete    | `NSCoding`, `NSCopying`, and concurrent `enumerateWithOptions(_:range:paramType:returnType:block:)` remain unimplemented                                            |
@@ -199,7 +199,7 @@
     | `RegularExpression`         | Mostly Complete | Substantial   | `NSCoding` remains unimplemented                                                                                                                                 |
     | `Scanner`                   | Mostly Complete | Incomplete    | `scanHex<T: _FloatLike>(_:locale:locationToScanFrom:to:)` and `localizedScannerWithString(_:)` remain unimplemented                                              |
     | `TextCheckingResult`        | Mostly Complete | Incomplete    | `NSCoding`, `NSCopying`, `resultType`, and `range(at:)` remain unimplemented                                                                                     |
-    | `NSAttributedString`        | Incomplete      | Incomplete    | `NSCoding`, `NS[Mutable]Copying`, `attributedSubstring(from:)`, `isEqual(to:)`, `init(NSAttributedString:)`, and `enumerateAttributes(...)` remain unimplemented |
+    | `NSAttributedString`        | Incomplete      | Incomplete    | `NSCoding`, `NS[Mutable]Copying`, `attributedSubstring(from:)`, `isEqual(to:)`, `init(NSAttributedString:)` remain unimplemented |
     | `NSMutableAttributedString` | Unimplemented   | Incomplete    | Only `addAttribute(_:value:range:)` is implemented                                                                                                               |
     | `NSCharacterSet`            | Mostly Complete | Incomplete    | `NSCoding` remains unimplemented                                                                                                                                 |
     | `NSMutableCharacterSet`     | Mostly Complete | None          | Decoding remains unimplemented                                                                                                                                   |
@@ -215,14 +215,14 @@
 
     | Entity Name                       | Status          | Test Coverage | Notes                                                                         |
     |-----------------------------------|-----------------|---------------|-------------------------------------------------------------------------------|
-    | `NSRange`                         | Mostly Complete | Incomplete    | `NSCoding` from non-keyed-coding archivers remains unimplemented              |
+    | `NSRange`                         | Complete 		  | Incomplete    | 															                |
     | `Decimal`                         | Unimplemented   | None          |                                                                               |
     | `NSDecimalNumber`                 | Unimplemented   | None          |                                                                               |
     | `NSDecimalNumberHandler`          | Unimplemented   | None          |                                                                               |
     | `CGPoint`                         | Complete        | Substantial   |                                                                               |
     | `CGSize`                          | Complete        | Substantial   |                                                                               |
     | `CGRect`                          | Complete        | Substantial   |                                                                               |
-    | `NSEdgeInsets`                    | Mostly Complete | None          | `NSCoding` from non-keyed-coding archivers remains unimplemented              |
+    | `NSEdgeInsets`                    | Mostly Complete | None          | 															                |
     | `NSGeometry`                      | Mostly Complete | Substantial   | `NSIntegralRectWithOptions` `.AlignRectFlipped` support remains unimplemented |
     | `CGFloat`                         | Complete        | Substantial   |                                                                               |
     | `AffineTransform`                 | Complete        | None          |                                                                               |
@@ -264,17 +264,17 @@
     | Entity Name    | Statues         | Test Coverage | Notes                                                                                                                         |
     |----------------|-----------------|---------------|-------------------------------------------------------------------------------------------------------------------------------|
     | `UserDefaults` | Incomplete      | None          | `dictionaryRepresentation()`, domain support, and forced objects remain unimplemented. Unit tests are currently commented out |
-    | `NSLocale`     | Mostly Complete | Incomplete    | `NSCoding` from non-keyed-coding archivers remains unimplemented. Only unit test asserts locale key constant names            |
+    | `NSLocale`     | Complete		   | Incomplete    | Only unit test asserts locale key constant names																             |
     | `Locale`       | Complete        | Incomplete    | Only unit test asserts value copying                                                                                          |
 
 * **OS**: Mechanisms for interacting with the operating system on a file system level as well as process and thread level
 
     | Entity Name      | Status          | Test Coverage | Notes                                                                                                                     |
     |------------------|-----------------|---------------|---------------------------------------------------------------------------------------------------------------------------|
-    | `FileHandle`     | Mostly Complete | Incomplete    | `NSCoding`, `nullDevice`, and background operations remain unimplemented                                                  |
+    | `FileHandle`     | Mostly Complete | Incomplete    | `NSCoding`, and background operations remain unimplemented                                                                |
     | `Pipe`           | Complete        | Incomplete    |                                                                                                                           |
     | `FileManager`    | Incomplete      | Incomplete    | URL searches, relationship lookups, item copying, cross-device moving, recursive linking, and others remain unimplemented |
-    | `Task`           | Mostly Complete | Substantial   | `interrupt()`, `terminate()`, `suspend()`, `resume()`, and `terminationReason` remain unimplemented                       |
+    | `Process`        | Mostly Complete | Substantial   | `interrupt()`, `terminate()`, `suspend()`, and `resume()` remain unimplemented                                            |
     | `Bundle`         | Mostly Complete | Incomplete    | `allBundles`, `init(for:)`, `unload()`, `classNamed()`, and `principalClass` remain unimplemented                         |
     | `ProcessInfo`    | Complete        | Substantial   |                                                                                                                           |
     | `Thread`         | Incomplete      | Incomplete    | `isMainThread`, `mainThread`, `name`, `callStackReturnAddresses`, and `callStackSymbols` remain unimplemented             |
@@ -290,15 +290,15 @@
 
     | Entity Name        | Status          | Test Coverage | Notes                                                                                                                           |
     |--------------------|-----------------|---------------|---------------------------------------------------------------------------------------------------------------------------------|
-    | `NSCalendar`       | Mostly Complete | None          | `NSCoding` from non-keyed-coding archivers, `autoupdatingCurrent`, and `enumerateDates` remain unimplemented                    |
-    | `NSDateComponents` | Mostly Complete | None          | `NSCoding` from non-keyed-coding archivers remains unimplemented                                                                |
+    | `NSCalendar`       | Complete		   | None          | `autoupdatingCurrent`, and `enumerateDates` remain unimplemented                    								  |
+    | `NSDateComponents` | Complete		   | None          | 								                                                                     |
     | `Calendar`         | Complete        | Incomplete    |                                                                                                                                 |
     | `DateComponents`   | Complete        | Incomplete    |                                                                                                                                 |
-    | `NSDate`           | Mostly Complete | Incomplete    | Encoding to non-keyed-coding archivers and `timeIntervalSinceReferenceDate` remain unimplemented                                |
+    | `NSDate`           | Complete		   | Incomplete    |                                    |
     | `NSDateInterval`   | Complete        | None          |                                                                                                                                 |
     | `DateInterval`     | Complete        | None          |                                                                                                                                 |
     | `Date`             | Complete        | Incomplete    |                                                                                                                                 |
-    | `NSTimeZone`       | Mostly Complete | Incomplete    | `local` and setting `abbreviationDictionary` remain unimplemented |
+    | `NSTimeZone`       | Mostly Complete | Incomplete    | `local`, `timeZoneDataVersion` and setting `abbreviationDictionary` remain unimplemented 					  |
     | `TimeZone`         | Complete        | Incomplete    |                                                                                                                                 |
 
 * **Notifications**: Classes for loosely coupling events from a set of many observers.
@@ -318,7 +318,7 @@
     | `NSData`                 | Complete        | Substantial   |                                   |
     | `NSMutableData`          | Complete        | Substantial   |                                   |
     | `Data`                   | Complete        | Substantial   |                                   |
-    | `NSProgress`             | Unimplemented   | None          |                                   |
+    | `NSProgress`             | Complete        | Substantial   |                                   |
     | `NSError`                | Complete        | None          |                                   |
     | `NSUUID`                 | Complete        | Substantial   |                                   |
     | `UUID`                   | Complete        | None          |                                   |
diff --git a/Foundation.xcodeproj/project.pbxproj b/Foundation.xcodeproj/project.pbxproj
index fd8717d..a1ace0d 100644
--- a/Foundation.xcodeproj/project.pbxproj
+++ b/Foundation.xcodeproj/project.pbxproj
@@ -283,7 +283,7 @@
 		5BF7AEAC1BCD51F9008F214A /* NSEnumerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BDC3F371BCC5DCB00ED97BB /* NSEnumerator.swift */; };
 		5BF7AEAD1BCD51F9008F214A /* NSError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BDC3F381BCC5DCB00ED97BB /* NSError.swift */; };
 		5BF7AEAE1BCD51F9008F214A /* NSFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BDC3F391BCC5DCB00ED97BB /* NSFormatter.swift */; };
-		5BF7AEAF1BCD51F9008F214A /* NSHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BDC3F3A1BCC5DCB00ED97BB /* NSHost.swift */; };
+		5BF7AEAF1BCD51F9008F214A /* Host.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BDC3F3A1BCC5DCB00ED97BB /* Host.swift */; };
 		5BF7AEB01BCD51F9008F214A /* NSLocale.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BDC3F3B1BCC5DCB00ED97BB /* NSLocale.swift */; };
 		5BF7AEB11BCD51F9008F214A /* NSLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BDC3F3C1BCC5DCB00ED97BB /* NSLock.swift */; };
 		5BF7AEB21BCD51F9008F214A /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BDC3F3D1BCC5DCB00ED97BB /* NSNumber.swift */; };
@@ -315,6 +315,7 @@
 		BDFDF0A71DFF5B3E00C04CC5 /* TestNSPersonNameComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = BDFDF0A61DFF5B3E00C04CC5 /* TestNSPersonNameComponents.swift */; };
 		BF8E65311DC3B3CB005AB5C3 /* TestNotification.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF8E65301DC3B3CB005AB5C3 /* TestNotification.swift */; };
 		CC5249C01D341D23007CB54D /* TestUnitConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC5249BF1D341D23007CB54D /* TestUnitConverter.swift */; };
+		CD1C7F7D1E303B47008E331C /* TestNSError.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD1C7F7C1E303B47008E331C /* TestNSError.swift */; };
 		CE19A88C1C23AA2300B4CB6A /* NSStringTestData.txt in Resources */ = {isa = PBXBuildFile; fileRef = CE19A88B1C23AA2300B4CB6A /* NSStringTestData.txt */; };
 		D31302011C30CEA900295652 /* NSConcreteValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = D31302001C30CEA900295652 /* NSConcreteValue.swift */; };
 		D370696E1C394FBF00295652 /* NSKeyedUnarchiver-RangeTest.plist in Resources */ = {isa = PBXBuildFile; fileRef = D370696D1C394FBF00295652 /* NSKeyedUnarchiver-RangeTest.plist */; };
@@ -702,7 +703,7 @@
 		5BDC3F371BCC5DCB00ED97BB /* NSEnumerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSEnumerator.swift; sourceTree = "<group>"; };
 		5BDC3F381BCC5DCB00ED97BB /* NSError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = NSError.swift; sourceTree = "<group>"; xcLanguageSpecificationIdentifier = xcode.lang.swift; };
 		5BDC3F391BCC5DCB00ED97BB /* NSFormatter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSFormatter.swift; sourceTree = "<group>"; };
-		5BDC3F3A1BCC5DCB00ED97BB /* NSHost.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSHost.swift; sourceTree = "<group>"; };
+		5BDC3F3A1BCC5DCB00ED97BB /* Host.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Host.swift; sourceTree = "<group>"; };
 		5BDC3F3B1BCC5DCB00ED97BB /* NSLocale.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = NSLocale.swift; sourceTree = "<group>"; xcLanguageSpecificationIdentifier = xcode.lang.swift; };
 		5BDC3F3C1BCC5DCB00ED97BB /* NSLock.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = NSLock.swift; sourceTree = "<group>"; xcLanguageSpecificationIdentifier = xcode.lang.swift; };
 		5BDC3F3D1BCC5DCB00ED97BB /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = NSNumber.swift; sourceTree = "<group>"; xcLanguageSpecificationIdentifier = xcode.lang.swift; };
@@ -759,6 +760,7 @@
 		C2A9D75B1C15C08B00993803 /* TestNSUUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSUUID.swift; sourceTree = "<group>"; };
 		C93559281C12C49F009FD6A9 /* TestNSAffineTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSAffineTransform.swift; sourceTree = "<group>"; };
 		CC5249BF1D341D23007CB54D /* TestUnitConverter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestUnitConverter.swift; sourceTree = "<group>"; };
+		CD1C7F7C1E303B47008E331C /* TestNSError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSError.swift; sourceTree = "<group>"; };
 		CE19A88B1C23AA2300B4CB6A /* NSStringTestData.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = NSStringTestData.txt; sourceTree = "<group>"; };
 		D3047AEB1C38BC3300295652 /* TestNSValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSValue.swift; sourceTree = "<group>"; };
 		D31302001C30CEA900295652 /* NSConcreteValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSConcreteValue.swift; sourceTree = "<group>"; };
@@ -1395,6 +1397,7 @@
 				EA54A6FA1DB16D53009E0809 /* TestObjCRuntime.swift */,
 				BF8E65301DC3B3CB005AB5C3 /* TestNotification.swift */,
 				BDFDF0A61DFF5B3E00C04CC5 /* TestNSPersonNameComponents.swift */,
+				CD1C7F7C1E303B47008E331C /* TestNSError.swift */,
 			);
 			name = Tests;
 			sourceTree = "<group>";
@@ -1513,7 +1516,7 @@
 				5BA9BEA31CF380E8009DBD6C /* URLRequest.swift */,
 				EADE0B601BD15DFF00C49C64 /* NSHTTPCookie.swift */,
 				EADE0B611BD15DFF00C49C64 /* NSHTTPCookieStorage.swift */,
-				5BDC3F3A1BCC5DCB00ED97BB /* NSHost.swift */,
+				5BDC3F3A1BCC5DCB00ED97BB /* Host.swift */,
 			);
 			name = URL;
 			sourceTree = "<group>";
@@ -2081,7 +2084,7 @@
 				D39A14011C2D6E0A00295652 /* NSKeyedUnarchiver.swift in Sources */,
 				5B4092101D1B304C0022B067 /* NSStringEncodings.swift in Sources */,
 				5BECBA381D1CAD7000B39B1F /* Measurement.swift in Sources */,
-				5BF7AEAF1BCD51F9008F214A /* NSHost.swift in Sources */,
+				5BF7AEAF1BCD51F9008F214A /* Host.swift in Sources */,
 				EADE0B4E1BD09E0800C49C64 /* NSAffineTransform.swift in Sources */,
 				EADE0BC71BD15E0000C49C64 /* NSXMLDocument.swift in Sources */,
 				5BDC3FCE1BCF17D300ED97BB /* NSCFDictionary.swift in Sources */,
@@ -2275,6 +2278,7 @@
 				5B13B3511C582D4C00651CE2 /* TestNSByteCountFormatter.swift in Sources */,
 				BDFDF0A71DFF5B3E00C04CC5 /* TestNSPersonNameComponents.swift in Sources */,
 				5B13B3501C582D4C00651CE2 /* TestUtils.swift in Sources */,
+				CD1C7F7D1E303B47008E331C /* TestNSError.swift in Sources */,
 				294E3C1D1CC5E19300E4F44C /* TestNSAttributedString.swift in Sources */,
 				5B13B3431C582D4C00651CE2 /* TestNSScanner.swift in Sources */,
 				5B13B3401C582D4C00651CE2 /* TestNSRange.swift in Sources */,
diff --git a/Foundation/Calendar.swift b/Foundation/Calendar.swift
index 678657a..f07c57e 100644
--- a/Foundation/Calendar.swift
+++ b/Foundation/Calendar.swift
@@ -1132,15 +1132,35 @@
 }
 
 extension Calendar : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable {
+    private var _kindDescription : String {
+        if self == .autoupdatingCurrent {
+            return "autoupdatingCurrent"
+        } else if self == .current {
+            return "current"
+        } else {
+            return "fixed"
+        }
+    }
+    
     public var description: String {
-        return _handle.map { $0.description }
+        return "\(identifier) (\(_kindDescription))"
     }
     
     public var debugDescription: String {
-        return _handle.map { $0.debugDescription }
+        return "\(identifier) (\(_kindDescription))"
     }
     
-    public var customMirror: Mirror { NSUnimplemented() }
+    public var customMirror: Mirror {
+        let children: [(label: String?, value: Any)] = [
+            (label: "identifier", value: identifier),
+            (label: "kind", value: _kindDescription),
+            (label: "locale", value: locale as Any),
+            (label: "timeZone", value: timeZone),
+            (label: "firstWeekDay", value: firstWeekday),
+            (label: "minimumDaysInFirstWeek", value: minimumDaysInFirstWeek)
+        ]
+        return Mirror(self, children: children, displayStyle: Mirror.DisplayStyle.struct)
+    }
 }
 
 extension Calendar: _ObjectTypeBridgeable {
diff --git a/Foundation/Data.swift b/Foundation/Data.swift
index 842f1ea..5bfdfe3 100644
--- a/Foundation/Data.swift
+++ b/Foundation/Data.swift
@@ -1277,7 +1277,7 @@
     /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
     @inline(__always)
     public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
-        if buffer.count == 0 { return }
+        if buffer.isEmpty { return }
         if !isKnownUniquelyReferenced(&_backing) {
             _backing = _backing.mutableCopy()
         }
diff --git a/Foundation/FoundationErrors.swift b/Foundation/FoundationErrors.swift
index 2e00148..7a6110f 100644
--- a/Foundation/FoundationErrors.swift
+++ b/Foundation/FoundationErrors.swift
@@ -1,58 +1,167 @@
 // This source file is part of the Swift.org open source project
 //
-// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
 // Licensed under Apache License v2.0 with Runtime Library Exception
 //
 // See http://swift.org/LICENSE.txt for license information
 // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
 //
 
+/// File-system operation attempted on non-existent file.
 public var NSFileNoSuchFileError: Int                        { return CocoaError.Code.fileNoSuchFile.rawValue }
+
+/// Failure to get a lock on file.
 public var NSFileLockingError: Int                           { return CocoaError.Code.fileLocking.rawValue }
+
+/// Read error, reason unknown.
 public var NSFileReadUnknownError: Int                       { return CocoaError.Code.fileReadUnknown.rawValue }
+
+/// Read error because of a permission problem.
 public var NSFileReadNoPermissionError: Int                  { return CocoaError.Code.fileReadNoPermission.rawValue }
+
+/// Read error because of an invalid file name.
 public var NSFileReadInvalidFileNameError: Int               { return CocoaError.Code.fileReadInvalidFileName.rawValue }
+
+/// Read error because of a corrupted file, bad format, or similar reason.
 public var NSFileReadCorruptFileError: Int                   { return CocoaError.Code.fileReadCorruptFile.rawValue }
+
+/// Read error because no such file was found.
 public var NSFileReadNoSuchFileError: Int                    { return CocoaError.Code.fileReadNoSuchFile.rawValue }
+
+/// Read error because the string encoding was not applicable.
+///
+/// Access the bad encoding from the `userInfo` dictionary using
+/// the `NSStringEncodingErrorKey` key.
 public var NSFileReadInapplicableStringEncodingError: Int    { return CocoaError.Code.fileReadInapplicableStringEncoding.rawValue }
+
+/// Read error because the specified URL scheme is unsupported.
 public var NSFileReadUnsupportedSchemeError: Int             { return CocoaError.Code.fileReadUnsupportedScheme.rawValue }
+
+/// Read error because the specified file was too large.
 public var NSFileReadTooLargeError: Int                      { return CocoaError.Code.fileReadTooLarge.rawValue }
+
+/// Read error because the string coding of the file could not be determined.
 public var NSFileReadUnknownStringEncodingError: Int         { return CocoaError.Code.fileReadUnknownStringEncoding.rawValue }
+
+/// Write error, reason unknown.
 public var NSFileWriteUnknownError: Int                      { return CocoaError.Code.fileWriteUnknown.rawValue }
+
+/// Write error because of a permission problem.
 public var NSFileWriteNoPermissionError: Int                 { return CocoaError.Code.fileWriteNoPermission.rawValue }
+
+/// Write error because of an invalid file name.
 public var NSFileWriteInvalidFileNameError: Int              { return CocoaError.Code.fileWriteInvalidFileName.rawValue }
+
+/// Write error returned when `FileManager` class’s copy, move,
+/// and link methods report errors when the destination file already exists.
 public var NSFileWriteFileExistsError: Int                   { return CocoaError.Code.fileWriteFileExists.rawValue }
+
+/// Write error because the string encoding was not applicable.
+///
+/// Access the bad encoding from the `userInfo` dictionary
+/// using the `NSStringEncodingErrorKey` key.
 public var NSFileWriteInapplicableStringEncodingError: Int   { return CocoaError.Code.fileWriteInapplicableStringEncoding.rawValue }
+
+/// Write error because the specified URL scheme is unsupported.
 public var NSFileWriteUnsupportedSchemeError: Int            { return CocoaError.Code.fileWriteUnsupportedScheme.rawValue }
+
+/// Write error because of a lack of disk space.
 public var NSFileWriteOutOfSpaceError: Int                   { return CocoaError.Code.fileWriteOutOfSpace.rawValue }
+
+/// Write error because because the volume is read only.
 public var NSFileWriteVolumeReadOnlyError: Int               { return CocoaError.Code.fileWriteVolumeReadOnly.rawValue }
+
 public var NSFileManagerUnmountUnknownError: Int             { return CocoaError.Code.fileManagerUnmountUnknown.rawValue }
+
 public var NSFileManagerUnmountBusyError: Int                { return CocoaError.Code.fileManagerUnmountBusy.rawValue }
+
+/// Key-value coding validation error.
 public var NSKeyValueValidationError: Int                    { return CocoaError.Code.keyValueValidation.rawValue }
+
+/// Formatting error (related to display of data).
 public var NSFormattingError: Int                            { return CocoaError.Code.formatting.rawValue }
+
+/// The user cancelled the operation (for example, by pressing Command-period).
+///
+/// This code is for errors that do not require a dialog displayed and might be
+/// candidates for special-casing.
 public var NSUserCancelledError: Int                         { return CocoaError.Code.userCancelled.rawValue }
+
+/// The feature is not supported, either because the file system
+/// lacks the feature, or required libraries are missing,
+/// or other similar reasons.
+///
+/// For example, some volumes may not support a Trash folder, so these methods
+/// will report failure by returning `false` or `nil` and
+/// an `NSError` with `NSFeatureUnsupportedError`.
 public var NSFeatureUnsupportedError: Int                    { return CocoaError.Code.featureUnsupported.rawValue }
+
+/// Executable is of a type that is not loadable in the current process.
 public var NSExecutableNotLoadableError: Int                 { return CocoaError.Code.executableNotLoadable.rawValue }
+
+/// Executable does not provide an architecture compatible with
+/// the current process.
 public var NSExecutableArchitectureMismatchError: Int        { return CocoaError.Code.executableArchitectureMismatch.rawValue }
+
+/// Executable has Objective-C runtime information incompatible
+/// with the current process.
 public var NSExecutableRuntimeMismatchError: Int             { return CocoaError.Code.executableRuntimeMismatch.rawValue }
+
+/// Executable cannot be loaded for some other reason, such as
+/// a problem with a library it depends on.
 public var NSExecutableLoadError: Int                        { return CocoaError.Code.executableLoad.rawValue }
+
+/// Executable fails due to linking issues.
 public var NSExecutableLinkError: Int                        { return CocoaError.Code.executableLink.rawValue }
+
+/// An error was encountered while parsing the property list.
 public var NSPropertyListReadCorruptError: Int               { return CocoaError.Code.propertyListReadCorrupt.rawValue }
+
+/// The version number of the property list is unable to be determined.
 public var NSPropertyListReadUnknownVersionError: Int        { return CocoaError.Code.propertyListReadUnknownVersion.rawValue }
+
+/// An stream error was encountered while reading the property list.
 public var NSPropertyListReadStreamError: Int                { return CocoaError.Code.propertyListReadStream.rawValue }
+
+/// An stream error was encountered while writing the property list.
 public var NSPropertyListWriteStreamError: Int               { return CocoaError.Code.propertyListWriteStream.rawValue }
+
 public var NSPropertyListWriteInvalidError: Int              { return CocoaError.Code.propertyListWriteInvalid.rawValue }
+
+/// The XPC connection was interrupted.
 public var NSXPCConnectionInterrupted: Int                   { return CocoaError.Code.xpcConnectionInterrupted.rawValue }
+
+/// The XPC connection was invalid.
 public var NSXPCConnectionInvalid: Int                       { return CocoaError.Code.xpcConnectionInvalid.rawValue }
+
+/// The XPC connection reply was invalid.
 public var NSXPCConnectionReplyInvalid: Int                  { return CocoaError.Code.xpcConnectionReplyInvalid.rawValue }
+
+/// The item has not been uploaded to iCloud by another device yet.
+///
+/// When this error occurs, you do not need to ask the system
+/// to start downloading the item. The system will download the item as soon
+/// as it can. If you want to know when the item becomes available,
+/// use an `NSMetadataQuer`y object to monitor changes to the file’s URL.
 public var NSUbiquitousFileUnavailableError: Int             { return CocoaError.Code.ubiquitousFileUnavailable.rawValue }
+
+/// The item could not be uploaded to iCloud because it would make
+/// the account go over its quota.
 public var NSUbiquitousFileNotUploadedDueToQuotaError: Int   { return CocoaError.Code.ubiquitousFileNotUploadedDueToQuota.rawValue }
+
+/// Connecting to the iCloud servers failed.
 public var NSUbiquitousFileUbiquityServerNotAvailable: Int   { return CocoaError.Code.ubiquitousFileUbiquityServerNotAvailable.rawValue }
+
 public var NSUserActivityHandoffFailedError: Int             { return CocoaError.Code.userActivityHandoffFailed.rawValue }
+
 public var NSUserActivityConnectionUnavailableError: Int     { return CocoaError.Code.userActivityConnectionUnavailable.rawValue }
+
 public var NSUserActivityRemoteApplicationTimedOutError: Int { return CocoaError.Code.userActivityRemoteApplicationTimedOut.rawValue }
+
 public var NSUserActivityHandoffUserInfoTooLargeError: Int   { return CocoaError.Code.userActivityHandoffUserInfoTooLarge.rawValue }
+
 public var NSCoderReadCorruptError: Int                      { return CocoaError.Code.coderReadCorrupt.rawValue }
+
 public var NSCoderValueNotFoundError: Int                    { return CocoaError.Code.coderValueNotFound.rawValue }
 
 #if os(OSX) || os(iOS)
diff --git a/Foundation/NSHost.swift b/Foundation/Host.swift
similarity index 100%
rename from Foundation/NSHost.swift
rename to Foundation/Host.swift
diff --git a/Foundation/Locale.swift b/Foundation/Locale.swift
index f5b9eab..29b58ba 100644
--- a/Foundation/Locale.swift
+++ b/Foundation/Locale.swift
@@ -428,13 +428,13 @@
             return _wrapped.hash
         }
     }
-}
 
-public func ==(lhs: Locale, rhs: Locale) -> Bool {
-    if lhs._autoupdating || rhs._autoupdating {
-        return lhs._autoupdating == rhs._autoupdating
-    } else {
-        return lhs._wrapped.isEqual(rhs._wrapped)
+    public static func ==(lhs: Locale, rhs: Locale) -> Bool {
+        if lhs._autoupdating || rhs._autoupdating {
+            return lhs._autoupdating == rhs._autoupdating
+        } else {
+            return lhs._wrapped.isEqual(rhs._wrapped)
+        }
     }
 }
 
diff --git a/Foundation/NSBundle.swift b/Foundation/NSBundle.swift
index 17d1dc1..b0814fb 100644
--- a/Foundation/NSBundle.swift
+++ b/Foundation/NSBundle.swift
@@ -271,22 +271,16 @@
         return CFBundleGetIdentifier(_bundle)?._swiftObject
     }
     
-    /// - Experiment: This is a draft API currently under consideration for official import into Foundation
-    /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
     open var infoDictionary: [String : Any]? {
         let cfDict: CFDictionary? = CFBundleGetInfoDictionary(_bundle)
         return _SwiftValue.fetch(cfDict) as? [String : Any]
     }
     
-    /// - Experiment: This is a draft API currently under consideration for official import into Foundation
-    /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
     open var localizedInfoDictionary: [String : Any]? {
         let cfDict: CFDictionary? = CFBundleGetLocalInfoDictionary(_bundle)
         return _SwiftValue.fetch(cfDict) as? [String : Any]
     }
     
-    /// - Experiment: This is a draft API currently under consideration for official import into Foundation
-    /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
     open func object(forInfoDictionaryKey key: String) -> Any? {
         if let localizedInfoDictionary = localizedInfoDictionary {
             return localizedInfoDictionary[key]
diff --git a/Foundation/NSCFArray.swift b/Foundation/NSCFArray.swift
index 17a13cf..b7ba101 100644
--- a/Foundation/NSCFArray.swift
+++ b/Foundation/NSCFArray.swift
@@ -62,7 +62,7 @@
     } else {
         let value = _SwiftValue.store(arr.object(at: index))
         let container: NSMutableDictionary
-        if arr._storage.count == 0 {
+        if arr._storage.isEmpty {
             container = NSMutableDictionary()
             arr._storage.append(container)
         } else {
@@ -84,7 +84,7 @@
             let index = idx + range.location
             let value = _SwiftValue.store(arr.object(at: index))
             let container: NSMutableDictionary
-            if arr._storage.count == 0 {
+            if arr._storage.isEmpty {
                 container = NSMutableDictionary()
                 arr._storage.append(container)
             } else {
diff --git a/Foundation/NSCache.swift b/Foundation/NSCache.swift
index b14a468..41e7fd7 100644
--- a/Foundation/NSCache.swift
+++ b/Foundation/NSCache.swift
@@ -175,11 +175,11 @@
 }
 
 public protocol NSCacheDelegate : NSObjectProtocol {
-    func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: AnyObject)
+    func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: Any)
 }
 
 extension NSCacheDelegate {
-    func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: AnyObject) {
+    func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: Any) {
         // Default implementation does nothing
     }
 }
diff --git a/Foundation/NSCalendar.swift b/Foundation/NSCalendar.swift
index 3391919..d350d6f 100644
--- a/Foundation/NSCalendar.swift
+++ b/Foundation/NSCalendar.swift
@@ -112,12 +112,14 @@
     }
 }
 
-public func ==(_ lhs: NSCalendar.Identifier, _ rhs: NSCalendar.Identifier) -> Bool {
-    return lhs.rawValue == rhs.rawValue
-}
+extension NSCalendar.Identifier {
+    public static func ==(_ lhs: NSCalendar.Identifier, _ rhs: NSCalendar.Identifier) -> Bool {
+        return lhs.rawValue == rhs.rawValue
+    }
 
-public func <(_ lhs: NSCalendar.Identifier, _ rhs: NSCalendar.Identifier) -> Bool {
-    return lhs.rawValue < rhs.rawValue
+    public static func <(_ lhs: NSCalendar.Identifier, _ rhs: NSCalendar.Identifier) -> Bool {
+        return lhs.rawValue < rhs.rawValue
+    }
 }
 
 open class NSCalendar : NSObject, NSCopying, NSSecureCoding {
@@ -603,8 +605,7 @@
             }
 
             return vector.withUnsafeMutableBufferPointer { (vecBuffer: inout UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in
-                _CFCalendarGetComponentDifferenceV(_cfObject, startingDate.timeIntervalSinceReferenceDate, resultDate.timeIntervalSinceReferenceDate, CFOptionFlags(opts.rawValue), compDesc, vecBuffer.baseAddress!, Int32(vector.count))
-                return false
+                return _CFCalendarGetComponentDifferenceV(_cfObject, startingDate.timeIntervalSinceReferenceDate, resultDate.timeIntervalSinceReferenceDate, CFOptionFlags(opts.rawValue), compDesc, vecBuffer.baseAddress!, Int32(vector.count))
             }
         }
         if res {
diff --git a/Foundation/NSCoder.swift b/Foundation/NSCoder.swift
index 949824d..fb42f3f 100644
--- a/Foundation/NSCoder.swift
+++ b/Foundation/NSCoder.swift
@@ -1,6 +1,6 @@
 // This source file is part of the Swift.org open source project
 //
-// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
 // Licensed under Apache License v2.0 with Runtime Library Exception
 //
 // See http://swift.org/LICENSE.txt for license information
@@ -8,24 +8,97 @@
 //
 
 extension NSCoder {
-    /*!
-     Describes the action an NSCoder should take when it encounters decode failures (e.g. corrupt data) for non-TopLevel decodes. Darwin platfrom supports exceptions here, and there may be other approaches supported in the future, so its included for completeness.
-     */
+
+    /// Describes the action an `NSCoder` should take when it encounters decode
+    /// failures (e.g. corrupt data) for non-TopLevel decodes. Darwin platfrom
+    /// supports exceptions here, and there may be other approaches supported
+    /// in the future, so its included for completeness.
     public enum DecodingFailurePolicy : Int {
         case setErrorAndReturn
     }
 }
 
 
+/// The `NSCoding` protocol declares the two methods that a class must implement
+/// so that instances of that class can be encoded and decoded. This capability
+/// provides the basis for archiving (where objects and other structures are
+/// stored on disk) and distribution (where objects are copied to different
+/// address spaces).
+///
+/// In keeping with object-oriented design principles, an object being encoded
+/// or decoded is responsible for encoding and decoding its instance variables.
+/// A coder instructs the object to do so by invoking `encode(with:)` or
+/// `init(coder:)`. `encode(with:)` instructs the object to encode its instance
+/// variables to the coder provided; this method can be invoked any number of
+/// times. `init(coder:)` instructs the object to initialize itself from data
+/// in the coder provided.
+/// Any object class that should be codable must adopt the NSCoding protocol and
+/// implement its methods.
 public protocol NSCoding {
+    
+    /// Encodes an instance of a conforming class using a given archiver.
+    ///
+    /// - Parameter aCoder: An archiver object.
     func encode(with aCoder: NSCoder)
+    
+    /// Initializes an object from data in a given unarchiver.
+    ///
+    /// - Parameter aDecoder: An unarchiver object.
     init?(coder aDecoder: NSCoder)
 }
 
+/// Conforming to the `NSSecureCoding` protocol indicates that an object handles
+/// encoding and decoding instances of itself in a manner that is robust against
+/// object substitution attacks.
+///
+/// Historically, many classes decoded instances of themselves like this:
+/// ```swift
+/// if let object = decoder.decodeObject(forKey: "myKey") as? MyClass {
+///     ...succeeds...
+/// } else {
+///     ...fail...
+/// }
+/// ```
+/// This technique is potentially unsafe because by the time you can verify
+/// the class type, the object has already been constructed, and if this is part
+/// of a collection class, potentially inserted into an object graph.
+///
+/// In order to conform to `NSSecureCoding`:
+/// - An object that does not override `init(coder:)` can conform to
+///   `NSSecureCoding` without any changes (assuming that it is a subclass
+///   of another class that conforms).
+/// - An object that does override `init(coder:)` must decode any enclosed
+///   objects using the `decodeObject(of:forKey:)` method. For example:
+///   ```swift
+///   let obj = decoder.decodeObject(of: MyClass.self, forKey: "myKey")
+///   ```
+///   In addition, the class must override its `NSSecureCoding` method to return
+///   `true`.
 public protocol NSSecureCoding : NSCoding {
+    
     static var supportsSecureCoding: Bool { get }
 }
 
+/// The `NSCoder` abstract class declares the interface used by concrete
+/// subclasses to transfer objects and other values between memory and some
+/// other format. This capability provides the basis for archiving (where
+/// objects and data items are stored on disk) and distribution (where objects
+/// and data items are copied between different processes or threads). The
+/// concrete subclasses provided by Foundation for these purposes are
+/// `NSKeyedArchiver` and `NSKeyedUnarchiver`. Concrete subclasses of `NSCoder`
+/// are referred to in general as coder classes, and instances of these classes
+/// as coder objects (or simply coders). A coder object that can only encode
+/// values is referred to as an encoder object, and one that can only decode
+/// values as a decoder object.
+///
+/// `NSCoder` operates on objects, scalars, C arrays, structures, and strings,
+/// and on pointers to these types. It does not handle types whose
+/// implementation varies across platforms, such as `UnsafeRawPointer`,
+/// closures, and long chains of pointers. A coder object stores object type
+/// information along with the data, so an object decoded from a stream of bytes
+/// is normally of the same class as the object that was originally encoded into
+/// the stream. An object can change its class when encoded, however; this is
+/// described in Archives and Serializations Programming Guide.
 open class NSCoder : NSObject {
     internal var _pendingBuffers = Array<(UnsafeMutableRawPointer, Int)>()
     
@@ -36,22 +109,77 @@
         }
     }
     
+    /// Must be overridden by subclasses to encode a single value residing at
+    /// `addr`, whose Objective-C type is given by `type`.
+    ///
+    /// `type` must contain exactly one type code.
+    ///
+    /// This method must be matched by a subsequent
+    /// `decodeValue(ofObjCType:at:)` call.
+    ///
+    /// - Parameters:
+    ///   - type: A type code.
+    ///   - addr: The address of the object to endcode.
     open func encodeValue(ofObjCType type: UnsafePointer<Int8>, at addr: UnsafeRawPointer) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Encodes a given `Data` object.
+    ///
+    /// Subclasses must override this method.
+    ///
+    /// This method must be matched by a subsequent `decodeData()` call.
+    ///
+    /// - Parameter data: The data to encode.
     open func encode(_ data: Data) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Decodes a single value, whose Objective-C type is given by `type`.
+    ///
+    /// `type` must contain exactly one type code, and the buffer specified by
+    /// `data` must be large enough to hold the value corresponding to that type
+    /// code.
+    ///
+    /// Subclasses must override this method and provide an implementation to
+    /// decode the value. In your overriding implementation, decode the value
+    /// into the buffer beginning at `data`.
+    ///
+    /// This method matches an `encodeValue(ofObjCType:at:)` call used during
+    /// encoding.
+    ///
+    /// - Parameters:
+    ///   - type: A type code.
+    ///   - data: The buffer to put the decoded value into.
     open func decodeValue(ofObjCType type: UnsafePointer<Int8>, at data: UnsafeMutableRawPointer) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Decodes and returns a `Data` object that was previously encoded with
+    /// `encode(_:)`. Subclasses must override this method.
+    ///
+    /// The implementation of your overriding method must match the
+    /// implementation of your `encode(_:)` method. For example, a typical
+    /// `encode(_:)` method encodes the number of bytes of data followed by
+    /// the bytes themselves. Your override of this method must read the number
+    /// of bytes, create a `Data` object of the appropriate size, and decode the
+    /// bytes into the new `Data` object.
+    ///
+    /// - Returns: The decoded data.
     open func decodeData() -> Data? {
         NSRequiresConcreteImplementation()
     }
     
+    /// This method is present for historical reasons and is not used with
+    /// keyed archivers.
+    ///
+    /// The version number does apply not to
+    /// `NSKeyedArchiver`/`NSKeyedUnarchiver`. A keyed archiver does not encode
+    /// class version numbers.
+    ///
+    /// - Parameter className: The class name.
+    /// - Returns: The version in effect for the class named `className` or
+    ///            `NSNotFound` if no class named `className` exists.
     open func version(forClassName className: String) -> Int {
         NSRequiresConcreteImplementation()
     }
@@ -60,16 +188,16 @@
         NSUnimplemented()
     }
    
-    /*!
-     @method decodeObjectOfClasses:forKey:
-        @abstract Decodes an object for the key, restricted to the specified classes.
-        @param classes An array of the expected classes.
-        @param key The code key.
-        @return The decoded object.
-        @discussion This function signature differs from Foundation OS X in that
-        classes is an array of Classes, not a NSSet. This is because AnyClass cannot
-        be casted to NSObject, nor is it Hashable.
-     */
+    /// Decodes an object for the key, restricted to the specified `classes`.
+    ///
+    /// This function signature differs from Darwin Foundation in that `classes`
+    /// is an array of classes, not a set. This is because `AnyClass` cannot
+    /// be casted to `NSObject`, nor is it `Hashable`.
+    ///
+    /// - Parameters:
+    ///   - classes:    An array of the expected classes.
+    ///   - key:        The code key.
+    /// - Returns:      The decoded object.
     open func decodeObject(of classes: [AnyClass]?, forKey key: String) -> Any? {
         NSUnimplemented()
     }
@@ -86,20 +214,30 @@
         NSUnimplemented()
     }
     
-    /*!
-     @method decodeTopLevelObjectOfClasses:
-     @abstract Decodes an top-level object for the key, restricted to the specified classes.
-     @param classes An array of the expected classes.
-     @param key The code key.
-     @return The decoded object.
-     @discussion This function signature differs from Foundation OS X in that
-     classes is an array of Classes, not a NSSet. This is because AnyClass cannot
-     be casted to NSObject, nor is it Hashable.
-     */
+    /// Decodes an top-level object for the key, restricted to the specified
+    /// `classes`.
+    ///
+    /// This function signature differs from Darwin Foundation in that `classes`
+    /// is an array of classes, not a set. This is because `AnyClass` cannot
+    /// be casted to `NSObject`, nor is it `Hashable`.
+    ///
+    /// - Parameters:
+    ///   - classes: An array of the expected classes.
+    ///   - key: The code key.
+    /// - Returns: The decoded object.
     open func decodeTopLevelObject(of classes: [AnyClass], forKey key: String) throws -> Any? {
         NSUnimplemented()
     }
     
+    /// Encodes `object`.
+    ///
+    /// `NSCoder`’s implementation simply invokes `encodeValue(ofObjCType:at:)`
+    /// to encode object. Subclasses can override this method to encode
+    /// a reference to object instead of object itself.
+    ///
+    /// This method must be matched by a subsequent `decodeObject()` call.
+    ///
+    /// - Parameter object: The object to encode.
     open func encode(_ object: Any?) {
         var object = object
         withUnsafePointer(to: &object) { (ptr: UnsafePointer<Any?>) -> Void in
@@ -107,26 +245,97 @@
         }
     }
     
+    /// Can be overridden by subclasses to encode an interconnected group of
+    /// Objective-C objects, starting with `rootObject`.
+    ///
+    /// `NSCoder`’s implementation simply invokes `encode(_:)`.
+    ///
+    /// This method must be matched by a subsequent `decodeObject()` call.
+    ///
+    /// - Parameter rootObject: The root object of the group to encode.
     open func encodeRootObject(_ rootObject: Any) {
         encode(rootObject)
     }
     
+    /// Can be overridden by subclasses to encode `anObject` so that a copy,
+    /// rather than a proxy, is created upon decoding.
+    ///
+    /// `NSCoder`’s implementation simply invokes `encode(_:)`.
+    ///
+    /// This method must be matched by a corresponding `decodeObject()` call.
+    ///
+    /// - Parameter anObject: The object to encode.
     open func encodeBycopyObject(_ anObject: Any?) {
         encode(anObject)
     }
     
+    /// Can be overridden by subclasses to encode `anObject` so that a proxy,
+    /// rather than a copy, is created upon decoding.
+    ///
+    /// `NSCoder`’s implementation simply invokes `encode(_:)`.
+    ///
+    /// This method must be matched by a corresponding `decodeObject()` call.
+    ///
+    /// - Parameter anObject: The object to encode.
     open func encodeByrefObject(_ anObject: Any?) {
         encode(anObject)
     }
     
+    /// Can be overridden by subclasses to conditionally encode `object`,
+    /// preserving common references to that object.
+    ///
+    /// In the overriding method, `object` should be encoded only if it’s
+    /// unconditionally encoded elsewhere (with any other `encode...Object`
+    /// method).
+    ///
+    /// This method must be matched by a subsequent `decodeObject()` call. Upon
+    /// decoding, if `object` was never encoded unconditionally,
+    /// `decodeObject()` returns `nil` in place of `object`. However, if
+    /// `object` was encoded unconditionally, all references to `object` must be
+    /// resolved.
+    ///
+    /// `NSCoder’s` implementation simply invokes `encode(_:)`.
+    ///
+    /// - Parameter object: The object to conditionally encode.
     open func encodeConditionalObject(_ object: Any?) {
         encode(object)
     }
     
+    /// Encodes an array of `count` items, whose Objective-C type is given by
+    /// `type`.
+    ///
+    /// The values are encoded from the buffer beginning at `array`. `type` must
+    /// contain exactly one type code. `NSCoder`’s implementation invokes
+    /// `encodeValue(ofObjCType:at:)` to encode the entire array of items.
+    /// Subclasses that implement the `encodeValue(ofObjCType:at:)` method do
+    /// not need to override this method.
+    ///
+    /// This method must be matched by a subsequent
+    /// `decodeArray(ofObjCType:count:at:)` call.
+    ///
+    /// - note: You should not use this method to encode C arrays of Objective-C
+    ///         objects. See `decodeArray(ofObjCType:count:at:)` for more
+    ///         details.
+    ///
+    /// - Parameters:
+    ///   - type:   A type code.
+    ///   - count:  The number of items in `array`.
+    ///   - array:  The buffer of items.
     open func encodeArray(ofObjCType type: UnsafePointer<Int8>, count: Int, at array: UnsafeRawPointer) {
         encodeValue(ofObjCType: "[\(count)\(String(cString: type))]", at: array)
     }
     
+    /// Encodes a buffer of data whose types are unspecified.
+    ///
+    /// The buffer to be encoded begins at `byteaddr`, and its length in bytes
+    /// is given by `length`.
+    ///
+    /// This method must be matched by a corresponding
+    /// `decodeBytes(withReturnedLength:)` call.
+    ///
+    /// - Parameters:
+    ///   - byteaddr:   The address of the buffer to encode.
+    ///   - length:     The length of the buffer.
     open func encodeBytes(_ byteaddr: UnsafeRawPointer?, length: Int) {
         var newLength = UInt32(length)
         withUnsafePointer(to: &newLength) { (ptr: UnsafePointer<UInt32>) -> Void in
@@ -138,6 +347,18 @@
         }
     }
     
+    /// Decodes an Objective-C object that was previously encoded with any of
+    /// the `encode...Object` methods.
+    ///
+    /// `NSCoder`’s implementation invokes `decodeValue(ofObjCType:at:)` to
+    /// decode the object data.
+    ///
+    /// Subclasses may need to override this method if they override any of the
+    /// corresponding `encode...Object` methods. For example, if an object was
+    /// encoded conditionally using the `encodeConditionalObject(_:)` method,
+    /// this method needs to check whether the object had actually been encoded.
+    ///
+    /// - Returns: The decoded object.
     open func decodeObject() -> Any? {
         if self.error != nil {
             return nil
@@ -170,84 +391,244 @@
     }
     */
     
+    /// Encodes the property list `aPropertyList`.
+    ///
+    /// `NSCoder`’s implementation invokes `encodeValue(ofObjCType:at:)`
+    /// to encode `aPropertyList`.
+    ///
+    /// This method must be matched by a subsequent `decodePropertyList()` call.
+    ///
+    /// - Parameter aPropertyList: The property list to encode.
     open func encodePropertyList(_ aPropertyList: Any) {
         NSUnimplemented()
     }
     
+    /// Decodes a property list that was previously encoded with
+    /// `encodePropertyList(_:)`.
+    ///
+    /// - Returns: The decoded property list.
     open func decodePropertyList() -> Any? {
         NSUnimplemented()
     }
     
+    /// The system version in effect for the archive.
+    ///
+    /// During encoding, the current version. During decoding, the version that
+    /// was in effect when the data was encoded.
+    ///
+    /// Subclasses that implement decoding must override this property to return
+    /// the system version of the data being decoded.
     open var systemVersion: UInt32 {
         return 1000
     }
     
+    /// A Boolean value that indicates whether the receiver supports keyed
+    /// coding of objects.
+    ///
+    /// `false` by default. Concrete subclasses that support keyed coding,
+    /// such as `NSKeyedArchiver`, need to override this property to return
+    /// `true`.
     open var allowsKeyedCoding: Bool {
         return false
     }
     
+    /// Encodes the object `objv` and associates it with the string `key`.
+    ///
+    /// Subclasses must override this method to identify multiple encodings
+    /// of `objv` and encode a reference to `objv` instead. For example,
+    /// `NSKeyedArchiver` detects duplicate objects and encodes a reference to
+    /// the original object rather than encode the same object twice.
+    ///
+    /// - Parameters:
+    ///   - objv:   The object to encode.
+    ///   - key:    The key to associate the object with.
     open func encode(_ objv: Any?, forKey key: String) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Conditionally encodes a reference to `objv` and associates it with
+    /// the string `key` only if `objv` has been unconditionally encoded with
+    /// `encode(_:forKey:)`.
+    ///
+    /// Subclasses must override this method if they support keyed coding.
+    ///
+    /// The encoded object is decoded with the `decodeObject(forKey:)` method.
+    /// If `objv` was never encoded unconditionally, `decodeObject(forKey:)`
+    /// returns `nil` in place of `objv`.
+    ///
+    /// - Parameters:
+    ///   - objv:   The object to conditionally encode.
+    ///   - key:    The key to associate the object with.
     open func encodeConditionalObject(_ objv: Any?, forKey key: String) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Encodes `boolv` and associates it with the string `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameters:
+    ///   - boolv:  The value to encode.
+    ///   - key:    The key to associate the value with.
     open func encode(_ boolv: Bool, forKey key: String) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Encodes the 32-bit integer `intv` and associates it with the string
+    /// `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameters:
+    ///   - intv:   The value to encode.
+    ///   - key:    The key to associate the value with.
     open func encode(_ intv: Int32, forKey key: String) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Encodes the 64-bit integer `intv` and associates it with the string
+    /// `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameters:
+    ///   - intv:   The value to encode.
+    ///   - key:    The key to associate the value with.
     open func encode(_ intv: Int64, forKey key: String) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Encodes `realv` and associates it with the string
+    /// `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameters:
+    ///   - intv:   The value to encode.
+    ///   - key:    The key to associate the value with.
     open func encode(_ realv: Float, forKey key: String) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Encodes `realv` and associates it with the string
+    /// `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameters:
+    ///   - intv:   The value to encode.
+    ///   - key:    The key to associate the value with.
     open func encode(_ realv: Double, forKey key: String) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Encodes a buffer of data, `bytesp`, whose length is specified by `lenv`,
+    /// and associates it with the string `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameters:
+    ///   - bytesp: The buffer of data to encode.
+    ///   - lenv:   The length of the buffer.
+    ///   - key:    The key to associate the data with.
     open func encodeBytes(_ bytesp: UnsafePointer<UInt8>?, length lenv: Int, forKey key: String) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Returns a Boolean value that indicates whether an encoded value is
+    /// available for a string.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// The string is passed as `key`.
+    ///
+    /// - Parameter key:    The key to test.
+    /// - Returns:          `true` if an encoded value is available for provided
+    ///                     `key`, otherwise `false`.
     open func containsValue(forKey key: String) -> Bool {
         NSRequiresConcreteImplementation()
     }
     
+    /// Decodes and returns an Objective-C object that was previously encoded
+    /// with `encode(_:forKey:)` or `encodeConditionalObject(_:forKey:)` and
+    /// associated with the string `key`.
+    ///
+    /// - Parameter key:    The key the object to be decoded is associated with.
+    /// - Returns:          The decoded object.
     open func decodeObject(forKey key: String) -> Any? {
         NSRequiresConcreteImplementation()
     }
     
+    /// Decodes and returns a Boolean value that was previously encoded with
+    /// `encode(_:forKey:)` and associated with the string `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameter key:    The key the value to be decoded is associated with.
+    /// - Returns:          The decoded value.
     open func decodeBool(forKey key: String) -> Bool {
         NSRequiresConcreteImplementation()
     }
     
     // NOTE: this equivalent to the decodeIntForKey: in Objective-C implementation
+    
+    /// Decodes and returns an int value that was previously encoded with
+    /// `encodeCInt(_:forKey:)` or `encode(_:forKey:)` and associated with
+    /// the string `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameter key:    The key the value to be decoded is associated with.
+    /// - Returns:          The decoded value.
     open func decodeCInt(forKey key: String) -> Int32 {
         
         NSRequiresConcreteImplementation()
     }
     
+    /// Decodes and returns a 32-bit integer value that was previously encoded
+    /// with `encodeCInt(_:forKey:)` or `encode(_:forKey:)` and associated with
+    /// the string `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameter key:    The key the value to be decoded is associated with.
+    /// - Returns:          The decoded value.
     open func decodeInt32(forKey key: String) -> Int32 {
         NSRequiresConcreteImplementation()
     }
     
+    /// Decodes and returns a 64-bit integer value that was previously encoded
+    /// with `encodeCInt(_:forKey:)` or `encode(_:forKey:)` and associated with
+    /// the string `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameter key:    The key the value to be decoded is associated with.
+    /// - Returns:          The decoded value.
     open func decodeInt64(forKey key: String) -> Int64 {
         NSRequiresConcreteImplementation()
     }
     
+    /// Decodes and returns a float value that was previously encoded
+    /// with `encodeCInt(_:forKey:)` or `encode(_:forKey:)` and associated with
+    /// the string `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameter key:    The key the value to be decoded is associated with.
+    /// - Returns:          The decoded value.
     open func decodeFloat(forKey key: String) -> Float {
         NSRequiresConcreteImplementation()
     }
     
+    /// Decodes and returns a double value that was previously encoded
+    /// with `encodeCInt(_:forKey:)` or `encode(_:forKey:)` and associated with
+    /// the string `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameter key:    The key the value to be decoded is associated with.
+    /// - Returns:          The decoded value.
     open func decodeDouble(forKey key: String) -> Double {
         NSRequiresConcreteImplementation()
     }
@@ -258,35 +639,61 @@
         NSRequiresConcreteImplementation()
     }
     */
-    /// - experimental: This method does not exist in the Darwin Foundation.
+
+    /// - Experiment: This method does not exist in the Darwin Foundation.
     open func withDecodedUnsafeBufferPointer<ResultType>(forKey key: String, body: (UnsafeBufferPointer<UInt8>?) throws -> ResultType) rethrows -> ResultType {
         NSRequiresConcreteImplementation()
     }
 
+    /// Encodes a given integer number and associates it with a given key.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameters:
+    ///   - intv:   The value to encode.
+    ///   - key:    The key to associate the value with.
     open func encode(_ intv: Int, forKey key: String) {
         NSRequiresConcreteImplementation()
     }
     
+    /// Decodes and returns an integer value that was previously encoded
+    /// with `encodeCInt(_:forKey:)` or `encode(_:forKey:)` and associated with
+    /// the string `key`.
+    ///
+    /// Subclasses must override this method if they perform keyed coding.
+    ///
+    /// - Parameter key:    The key the value to be decoded is associated with.
+    /// - Returns:          The decoded value.
     open func decodeInteger(forKey key: String) -> Int {
         NSRequiresConcreteImplementation()
     }
     
+    /// Boolean value that indicates whether the coder requires secure coding.
+    ///
+    /// `true` if this coder requires secure coding; `false` otherwise.
+    ///
+    /// Secure coders check a set of allowed classes before decoding objects,
+    /// and all objects must implement the `NSSecureCoding` protocol.
     open var requiresSecureCoding: Bool {
         return false
     }
     
-    open func decodePropertyListForKey(_ key: String) -> Any? {
+    /// Returns a decoded property list for the specified key.
+    ///
+    /// - Parameter key:    The coder key.
+    /// - Returns:          A decoded object containing a property list.
+    open func decodePropertyList(forKey key: String) -> Any? {
         NSUnimplemented()
     }
-    
-    /*!
-     @property allowedClasses
-     @abstract The set of coded classes allowed for secure coding. (read-only)
-     @discussion This property type differs from Foundation OS X in that
-     classes is an array of Classes, not a Set. This is because AnyClass is not
-     hashable.
-     */
-    /// - Experiment: This is a draft API currently under consideration for official import into Foundation
+
+    /// The array of coded classes allowed for secure coding.
+    ///
+    /// This property type differs from Darwin Foundation in that `classes` is
+    /// an array of classes, not a set. This is because `AnyClass` is not
+    /// `Hashable`.
+    ///
+    /// - Experiment: This is a draft API currently under consideration for
+    ///               official import into Foundation.
     open var allowedClasses: [AnyClass]? {
         NSUnimplemented()
     }
@@ -304,6 +711,7 @@
     open var decodingFailurePolicy: NSCoder.DecodingFailurePolicy {
         return .setErrorAndReturn
     }
+    
     open var error: Error? {
         NSRequiresConcreteImplementation()
     }
diff --git a/Foundation/NSCompoundPredicate.swift b/Foundation/NSCompoundPredicate.swift
index c7a83ac..0efd6ab 100644
--- a/Foundation/NSCompoundPredicate.swift
+++ b/Foundation/NSCompoundPredicate.swift
@@ -20,7 +20,7 @@
 
 open class NSCompoundPredicate : NSPredicate {
     public init(type: LogicalType, subpredicates: [NSPredicate]) {
-        if type == .not && subpredicates.count == 0 {
+        if type == .not && subpredicates.isEmpty {
             preconditionFailure("Unsupported predicate count of \(subpredicates.count) for \(type)")
         }
 
diff --git a/Foundation/NSData.swift b/Foundation/NSData.swift
index 0d1918b..fe42548 100644
--- a/Foundation/NSData.swift
+++ b/Foundation/NSData.swift
@@ -800,7 +800,7 @@
             if options.contains(.endLineWithLineFeed) { separator.append(10) }
             
             //if the kind of line ending to insert is not specified, the default line ending is Carriage Return + Line Feed.
-            if separator.count == 0 {separator = [13,10]}
+            if separator.isEmpty { separator = [13,10] }
             
             return (lineLength,separator)
         }()
diff --git a/Foundation/NSDecimal.swift b/Foundation/NSDecimal.swift
index 66b402a..02a7fd2 100644
--- a/Foundation/NSDecimal.swift
+++ b/Foundation/NSDecimal.swift
@@ -1394,7 +1394,7 @@
     return result.pointee.multiply(byPowerOf10: power)
 }
 
-public func NSDecimalString(_ dcm: UnsafePointer<Decimal>, _ locale: AnyObject?) -> String {
+public func NSDecimalString(_ dcm: UnsafePointer<Decimal>, _ locale: Any?) -> String {
     guard locale == nil else {
         fatalError("Locale not supported: \(locale!)")
     }
diff --git a/Foundation/NSDecimalNumber.swift b/Foundation/NSDecimalNumber.swift
index 445a9ef..d114bf8 100644
--- a/Foundation/NSDecimalNumber.swift
+++ b/Foundation/NSDecimalNumber.swift
@@ -106,7 +106,7 @@
     public convenience init(string numberValue: String?) {
         self.init(decimal: Decimal(string: numberValue ?? "") ?? Decimal.nan)
     }
-    public convenience init(string numberValue: String?, locale: AnyObject?) {
+    public convenience init(string numberValue: String?, locale: Any?) {
         self.init(decimal: Decimal(string: numberValue ?? "", locale: locale as? Locale) ?? Decimal.nan)
     }
 
diff --git a/Foundation/NSDictionary.swift b/Foundation/NSDictionary.swift
index 5c27c9e..e165060 100644
--- a/Foundation/NSDictionary.swift
+++ b/Foundation/NSDictionary.swift
@@ -644,7 +644,7 @@
     As for any usage of hashing, is recommended that the keys have a well-distributed implementation of -hash, and the hash codes must satisfy the hash/isEqual: invariant.
     Keys with duplicate hash codes are allowed, but will cause lower performance and increase memory usage.
     */
-    open class func sharedKeySet(forKeys keys: [NSCopying]) -> AnyObject { NSUnimplemented() }
+    open class func sharedKeySet(forKeys keys: [NSCopying]) -> Any { NSUnimplemented() }
 }
 
 extension NSMutableDictionary {
@@ -655,7 +655,7 @@
     If keyset is nil, an exception is thrown.
     If keyset is not an object returned by +sharedKeySetForKeys:, an exception is thrown.
     */
-    public convenience init(sharedKeySet keyset: AnyObject) { NSUnimplemented() }
+    public convenience init(sharedKeySet keyset: Any) { NSUnimplemented() }
 }
 
 extension NSDictionary : ExpressibleByDictionaryLiteral { }
diff --git a/Foundation/NSError.swift b/Foundation/NSError.swift
index d1627b9..3c6e255 100644
--- a/Foundation/NSError.swift
+++ b/Foundation/NSError.swift
@@ -144,14 +144,14 @@
         return userInfo[NSHelpAnchorErrorKey] as? String
     }
     
-    internal typealias NSErrorProvider = (_ error: NSError, _ key: String) -> AnyObject?
+    internal typealias NSErrorProvider = (_ error: NSError, _ key: String) -> Any?
     internal static var userInfoProviders = [String: NSErrorProvider]()
     
-    open class func setUserInfoValueProvider(forDomain errorDomain: String, provider: (/* @escaping */ (NSError, String) -> AnyObject?)?) {
+    open class func setUserInfoValueProvider(forDomain errorDomain: String, provider: (/* @escaping */ (NSError, String) -> Any?)?) {
         NSError.userInfoProviders[errorDomain] = provider
     }
 
-    open class func userInfoValueProvider(forDomain errorDomain: String) -> ((NSError, String) -> AnyObject?)? {
+    open class func userInfoValueProvider(forDomain errorDomain: String) -> ((NSError, String) -> Any?)? {
         return NSError.userInfoProviders[errorDomain]
     }
     
@@ -222,9 +222,9 @@
 /// NSErrorRecoveryAttempting, which is used by NSError when it
 /// attempts recovery from an error.
 class _NSErrorRecoveryAttempter {
-    func attemptRecovery(fromError nsError: NSError,
+    func attemptRecovery(fromError error: Error,
         optionIndex recoveryOptionIndex: Int) -> Bool {
-        let error = nsError as Error as! RecoverableError
+        let error = error as! RecoverableError
         return error.attemptRecovery(optionIndex: recoveryOptionIndex)
   }
 }
@@ -288,7 +288,8 @@
 public extension Error {
     /// Retrieve the localized description for this error.
     var localizedDescription: String {
-        return NSError(domain: _domain, code: _code, userInfo: nil).localizedDescription
+        let defaultUserInfo = _swift_Foundation_getErrorDefaultUserInfo(self) as! [String : Any]
+        return NSError(domain: _domain, code: _code, userInfo: defaultUserInfo).localizedDescription
     }
 }
 
diff --git a/Foundation/NSFileManager.swift b/Foundation/NSFileManager.swift
index df4d0fd..430ccac 100644
--- a/Foundation/NSFileManager.swift
+++ b/Foundation/NSFileManager.swift
@@ -274,7 +274,6 @@
      
         This method replaces fileAttributesAtPath:traverseLink:.
      */
-    /// - Experiment: Note that the return type of this function is different than on Darwin Foundation (Any instead of AnyObject). This is likely to change once we have a more complete story for bridging in place.
     open func attributesOfItem(atPath path: String) throws -> [FileAttributeKey : Any] {
         var s = stat()
         guard lstat(path, &s) == 0 else {
@@ -373,7 +372,23 @@
     }
     
     open func copyItem(atPath srcPath: String, toPath dstPath: String) throws {
-        NSUnimplemented()
+        guard
+            let attrs = try? attributesOfItem(atPath: srcPath),
+            let fileType = attrs[.type] as? FileAttributeType
+            else {
+                return
+        }
+        if fileType == .typeDirectory {
+            try createDirectory(atPath: dstPath, withIntermediateDirectories: false, attributes: nil)
+            let subpaths = try subpathsOfDirectory(atPath: srcPath)
+            for subpath in subpaths {
+                try copyItem(atPath: srcPath + "/" + subpath, toPath: dstPath + "/" + subpath)
+            }
+        } else {
+            if createFile(atPath: dstPath, contents: contents(atPath: srcPath), attributes: nil) == false {
+                throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue, userInfo: [NSFilePathErrorKey : NSString(string: dstPath)])
+            }
+        }
     }
     
     open func moveItem(atPath srcPath: String, toPath dstPath: String) throws {
diff --git a/Foundation/NSGeometry.swift b/Foundation/NSGeometry.swift
index d4aa43b..46d5ee2 100644
--- a/Foundation/NSGeometry.swift
+++ b/Foundation/NSGeometry.swift
@@ -25,10 +25,10 @@
     }
 }
 
-extension CGPoint: Equatable { }
-
-public func ==(lhs: CGPoint, rhs: CGPoint) -> Bool {
-    return lhs.x == rhs.x && lhs.y == rhs.y
+extension CGPoint: Equatable {
+    public static func ==(lhs: CGPoint, rhs: CGPoint) -> Bool {
+        return lhs.x == rhs.x && lhs.y == rhs.y
+    }
 }
 
 extension CGPoint: NSSpecialValueCoding {
@@ -41,14 +41,14 @@
         guard aDecoder.allowsKeyedCoding else {
             preconditionFailure("Unkeyed coding is unsupported.")
         }
-        self = aDecoder.decodePointForKey("NS.pointval")
+        self = aDecoder.decodePoint(forKey: "NS.pointval")
     }
     
     func encodeWithCoder(_ aCoder: NSCoder) {
         guard aCoder.allowsKeyedCoding else {
             preconditionFailure("Unkeyed coding is unsupported.")
         }
-        aCoder.encodePoint(self, forKey: "NS.pointval")
+        aCoder.encode(self, forKey: "NS.pointval")
     }
     
     static func objCType() -> String {
@@ -88,10 +88,10 @@
     }
 }
 
-extension CGSize: Equatable { }
-
-public func ==(lhs: CGSize, rhs: CGSize) -> Bool {
-    return lhs.width == rhs.width && lhs.height == rhs.height
+extension CGSize: Equatable {
+    public static func ==(lhs: CGSize, rhs: CGSize) -> Bool {
+        return lhs.width == rhs.width && lhs.height == rhs.height
+    }
 }
 
 extension CGSize: NSSpecialValueCoding {
@@ -104,14 +104,14 @@
         guard aDecoder.allowsKeyedCoding else {
             preconditionFailure("Unkeyed coding is unsupported.")
         }
-        self = aDecoder.decodeSizeForKey("NS.sizeval")
+        self = aDecoder.decodeSize(forKey: "NS.sizeval")
     }
     
     func encodeWithCoder(_ aCoder: NSCoder) {
         guard aCoder.allowsKeyedCoding else {
             preconditionFailure("Unkeyed coding is unsupported.")
         }
-        aCoder.encodeSize(self, forKey: "NS.sizeval")
+        aCoder.encode(self, forKey: "NS.sizeval")
     }
     
     static func objCType() -> String {
@@ -151,10 +151,10 @@
     }
 }
 
-extension CGRect: Equatable { }
-
-public func ==(lhs: CGRect, rhs: CGRect) -> Bool {
-    return lhs.origin == rhs.origin && lhs.size == rhs.size
+extension CGRect: Equatable {
+    public static func ==(lhs: CGRect, rhs: CGRect) -> Bool {
+        return lhs.origin == rhs.origin && lhs.size == rhs.size
+    }
 }
 
 public typealias NSPoint = CGPoint
@@ -186,14 +186,14 @@
         guard aDecoder.allowsKeyedCoding else {
             preconditionFailure("Unkeyed coding is unsupported.")
         }
-        self = aDecoder.decodeRectForKey("NS.rectval")
+        self = aDecoder.decodeRect(forKey: "NS.rectval")
     }
     
     func encodeWithCoder(_ aCoder: NSCoder) {
         guard aCoder.allowsKeyedCoding else {
             preconditionFailure("Unkeyed coding is unsupported.")
         }
-        aCoder.encodeRect(self, forKey: "NS.rectval")
+        aCoder.encode(self, forKey: "NS.rectval")
     }
     
     static func objCType() -> String {
@@ -321,38 +321,38 @@
     }
 }
 
-public struct NSAlignmentOptions : OptionSet {
+public struct AlignmentOptions : OptionSet {
     public var rawValue : UInt64
     public init(rawValue: UInt64) { self.rawValue = rawValue }
     
-    public static let AlignMinXInward = NSAlignmentOptions(rawValue: 1 << 0)
-    public static let AlignMinYInward = NSAlignmentOptions(rawValue: 1 << 1)
-    public static let AlignMaxXInward = NSAlignmentOptions(rawValue: 1 << 2)
-    public static let AlignMaxYInward = NSAlignmentOptions(rawValue: 1 << 3)
-    public static let AlignWidthInward = NSAlignmentOptions(rawValue: 1 << 4)
-    public static let AlignHeightInward = NSAlignmentOptions(rawValue: 1 << 5)
+    public static let alignMinXInward = AlignmentOptions(rawValue: 1 << 0)
+    public static let alignMinYInward = AlignmentOptions(rawValue: 1 << 1)
+    public static let alignMaxXInward = AlignmentOptions(rawValue: 1 << 2)
+    public static let alignMaxYInward = AlignmentOptions(rawValue: 1 << 3)
+    public static let alignWidthInward = AlignmentOptions(rawValue: 1 << 4)
+    public static let alignHeightInward = AlignmentOptions(rawValue: 1 << 5)
     
-    public static let AlignMinXOutward = NSAlignmentOptions(rawValue: 1 << 8)
-    public static let AlignMinYOutward = NSAlignmentOptions(rawValue: 1 << 9)
-    public static let AlignMaxXOutward = NSAlignmentOptions(rawValue: 1 << 10)
-    public static let AlignMaxYOutward = NSAlignmentOptions(rawValue: 1 << 11)
-    public static let AlignWidthOutward = NSAlignmentOptions(rawValue: 1 << 12)
-    public static let AlignHeightOutward = NSAlignmentOptions(rawValue: 1 << 13)
+    public static let alignMinXOutward = AlignmentOptions(rawValue: 1 << 8)
+    public static let alignMinYOutward = AlignmentOptions(rawValue: 1 << 9)
+    public static let alignMaxXOutward = AlignmentOptions(rawValue: 1 << 10)
+    public static let alignMaxYOutward = AlignmentOptions(rawValue: 1 << 11)
+    public static let alignWidthOutward = AlignmentOptions(rawValue: 1 << 12)
+    public static let alignHeightOutward = AlignmentOptions(rawValue: 1 << 13)
     
-    public static let AlignMinXNearest = NSAlignmentOptions(rawValue: 1 << 16)
-    public static let AlignMinYNearest = NSAlignmentOptions(rawValue: 1 << 17)
-    public static let AlignMaxXNearest = NSAlignmentOptions(rawValue: 1 << 18)
-    public static let AlignMaxYNearest = NSAlignmentOptions(rawValue: 1 << 19)
-    public static let AlignWidthNearest = NSAlignmentOptions(rawValue: 1 << 20)
-    public static let AlignHeightNearest = NSAlignmentOptions(rawValue: 1 << 21)
+    public static let alignMinXNearest = AlignmentOptions(rawValue: 1 << 16)
+    public static let alignMinYNearest = AlignmentOptions(rawValue: 1 << 17)
+    public static let alignMaxXNearest = AlignmentOptions(rawValue: 1 << 18)
+    public static let alignMaxYNearest = AlignmentOptions(rawValue: 1 << 19)
+    public static let alignWidthNearest = AlignmentOptions(rawValue: 1 << 20)
+    public static let alignHeightNearest = AlignmentOptions(rawValue: 1 << 21)
 
     // pass this if the rect is in a flipped coordinate system. This allows 0.5 to be treated in a visually consistent way.
-    public static let AlignRectFlipped = NSAlignmentOptions(rawValue: 1 << 63)
+    public static let alignRectFlipped = AlignmentOptions(rawValue: 1 << 63)
     
     // convenience combinations
-    public static let AlignAllEdgesInward = [NSAlignmentOptions.AlignMinXInward, NSAlignmentOptions.AlignMaxXInward, NSAlignmentOptions.AlignMinYInward, NSAlignmentOptions.AlignMaxYInward]
-    public static let AlignAllEdgesOutward = [NSAlignmentOptions.AlignMinXOutward, NSAlignmentOptions.AlignMaxXOutward, NSAlignmentOptions.AlignMinYOutward, NSAlignmentOptions.AlignMaxYOutward]
-    public static let AlignAllEdgesNearest = [NSAlignmentOptions.AlignMinXNearest, NSAlignmentOptions.AlignMaxXNearest, NSAlignmentOptions.AlignMinYNearest, NSAlignmentOptions.AlignMaxYNearest]
+    public static let alignAllEdgesInward: AlignmentOptions = [.alignMinXInward, .alignMaxXInward, .alignMinYInward, .alignMaxYInward]
+    public static let alignAllEdgesOutward: AlignmentOptions = [.alignMinXOutward, .alignMaxXOutward, .alignMinYOutward, .alignMaxYOutward]
+    public static let alignAllEdgesNearest: AlignmentOptions = [.alignMinXNearest, .alignMaxXNearest, .alignMinYNearest, .alignMaxYNearest]
 }
 
 public let NSZeroPoint: NSPoint = NSPoint()
@@ -429,12 +429,12 @@
         return NSZeroRect
     }
     
-    return NSIntegralRectWithOptions(aRect, [.AlignMinXOutward, .AlignMaxXOutward, .AlignMinYOutward, .AlignMaxYOutward])
+    return NSIntegralRectWithOptions(aRect, [.alignMinXOutward, .alignMaxXOutward, .alignMinYOutward, .alignMaxYOutward])
 }
-public func NSIntegralRectWithOptions(_ aRect: NSRect, _ opts: NSAlignmentOptions) -> NSRect {
+public func NSIntegralRectWithOptions(_ aRect: NSRect, _ opts: AlignmentOptions) -> NSRect {
     let listOfOptionsIsInconsistentErrorMessage = "List of options is inconsistent"
     
-    if opts.contains(.AlignRectFlipped) {
+    if opts.contains(.alignRectFlipped) {
         NSUnimplemented()
     }
 
@@ -453,81 +453,81 @@
     }
     
 
-    if opts.contains(.AlignWidthInward) && width != 0 {
+    if opts.contains(.alignWidthInward) && width != 0 {
         guard width.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         width = floor(aRect.size.width.native)
     }
-    if opts.contains(.AlignHeightInward) && height != 0 {
+    if opts.contains(.alignHeightInward) && height != 0 {
         guard height.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         height = floor(aRect.size.height.native)
     }
-    if opts.contains(.AlignWidthOutward) && width != 0 {
+    if opts.contains(.alignWidthOutward) && width != 0 {
         guard width.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         width = ceil(aRect.size.width.native)
     }
-    if opts.contains(.AlignHeightOutward) && height != 0 {
+    if opts.contains(.alignHeightOutward) && height != 0 {
         guard height.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         height = ceil(aRect.size.height.native)
     }
-    if opts.contains(.AlignWidthNearest) && width != 0 {
+    if opts.contains(.alignWidthNearest) && width != 0 {
         guard width.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         width = round(aRect.size.width.native)
     }
-    if opts.contains(.AlignHeightNearest) && height != 0 {
+    if opts.contains(.alignHeightNearest) && height != 0 {
         guard height.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         height = round(aRect.size.height.native)
     }
 
     
-    if opts.contains(.AlignMinXInward) {
+    if opts.contains(.alignMinXInward) {
         guard minX.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         minX = ceil(aRect.origin.x.native)
     }
-    if opts.contains(.AlignMinYInward) {
+    if opts.contains(.alignMinYInward) {
         guard minY.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         minY = ceil(aRect.origin.y.native)
     }
-    if opts.contains(.AlignMaxXInward) {
+    if opts.contains(.alignMaxXInward) {
         guard maxX.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         maxX = floor(aRect.origin.x.native + aRect.size.width.native)
     }
-    if opts.contains(.AlignMaxYInward) {
+    if opts.contains(.alignMaxYInward) {
         guard maxY.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         maxY = floor(aRect.origin.y.native + aRect.size.height.native)
     }
 
     
-    if opts.contains(.AlignMinXOutward) {
+    if opts.contains(.alignMinXOutward) {
         guard minX.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         minX = floor(aRect.origin.x.native)
     }
-    if opts.contains(.AlignMinYOutward) {
+    if opts.contains(.alignMinYOutward) {
         guard minY.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         minY = floor(aRect.origin.y.native)
     }
-    if opts.contains(.AlignMaxXOutward) {
+    if opts.contains(.alignMaxXOutward) {
         guard maxX.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         maxX = ceil(aRect.origin.x.native + aRect.size.width.native)
     }
-    if opts.contains(.AlignMaxYOutward) {
+    if opts.contains(.alignMaxYOutward) {
         guard maxY.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         maxY = ceil(aRect.origin.y.native + aRect.size.height.native)
     }
     
 
-    if opts.contains(.AlignMinXNearest) {
+    if opts.contains(.alignMinXNearest) {
         guard minX.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         minX = round(aRect.origin.x.native)
     }
-    if opts.contains(.AlignMinYNearest) {
+    if opts.contains(.alignMinYNearest) {
         guard minY.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         minY = round(aRect.origin.y.native)
     }
-    if opts.contains(.AlignMaxXNearest) {
+    if opts.contains(.alignMaxXNearest) {
         guard maxX.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         maxX = round(aRect.origin.x.native + aRect.size.width.native)
     }
-    if opts.contains(.AlignMaxYNearest) {
+    if opts.contains(.alignMaxYNearest) {
         guard maxY.isNaN else { fatalError(listOfOptionsIsInconsistentErrorMessage) }
         maxY = round(aRect.origin.y.native + aRect.size.height.native)
     }
@@ -807,7 +807,7 @@
 
 extension NSCoder {
     
-    public func encodePoint(_ point: NSPoint) {
+    public func encode(_ point: NSPoint) {
         self._encodeCGFloat(point.x)
         self._encodeCGFloat(point.y)
     }
@@ -816,7 +816,7 @@
         return NSPoint(x: _decodeCGFloat(), y: _decodeCGFloat())
     }
     
-    public func encodeSize(_ size: NSSize) {
+    public func encode(_ size: NSSize) {
         self._encodeCGFloat(size.width)
         self._encodeCGFloat(size.height)
     }
@@ -825,9 +825,9 @@
         return NSSize(width: _decodeCGFloat(), height: _decodeCGFloat())
     }
     
-    public func encodeRect(_ rect: NSRect) {
-        self.encodePoint(rect.origin)
-        self.encodeSize(rect.size)
+    public func encode(_ rect: NSRect) {
+        self.encode(rect.origin)
+        self.encode(rect.size)
     }
     
     public func decodeRect() -> NSRect {
@@ -837,19 +837,19 @@
 
 extension NSCoder {
     
-    public func encodePoint(_ point: NSPoint, forKey key: String) {
+    public func encode(_ point: NSPoint, forKey key: String) {
         self.encode(NSStringFromPoint(point)._bridgeToObjectiveC(), forKey: key)
     }
     
-    public func encodeSize(_ size: NSSize, forKey key: String) {
+    public func encode(_ size: NSSize, forKey key: String) {
         self.encode(NSStringFromSize(size)._bridgeToObjectiveC(), forKey: key)
     }
     
-    public func encodeRect(_ rect: NSRect, forKey key: String) {
+    public func encode(_ rect: NSRect, forKey key: String) {
         self.encode(NSStringFromRect(rect)._bridgeToObjectiveC(), forKey: key)
     }
     
-    public func decodePointForKey(_ key: String) -> NSPoint {
+    public func decodePoint(forKey key: String) -> NSPoint {
         if let string = self.decodeObject(of: NSString.self, forKey: key) {
             return NSPointFromString(String._unconditionallyBridgeFromObjectiveC(string))
         } else {
@@ -857,7 +857,7 @@
         }
     }
     
-    public func decodeSizeForKey(_ key: String) -> NSSize {
+    public func decodeSize(forKey key: String) -> NSSize {
         if let string = self.decodeObject(of: NSString.self, forKey: key) {
             return NSSizeFromString(String._unconditionallyBridgeFromObjectiveC(string))
         } else {
@@ -865,7 +865,7 @@
         }
     }
     
-    public func decodeRectForKey(_ key: String) -> NSRect {
+    public func decodeRect(forKey key: String) -> NSRect {
         if let string = self.decodeObject(of: NSString.self, forKey: key) {
             return NSRectFromString(String._unconditionallyBridgeFromObjectiveC(string))
         } else {
diff --git a/Foundation/NSHTTPCookie.swift b/Foundation/NSHTTPCookie.swift
index f78dd5d..b2c629f 100644
--- a/Foundation/NSHTTPCookie.swift
+++ b/Foundation/NSHTTPCookie.swift
@@ -255,7 +255,7 @@
         _domain = canonicalDomain
 
         if let
-            secureString = properties[.secure] as? String, secureString.characters.count > 0
+            secureString = properties[.secure] as? String, !secureString.characters.isEmpty
         {
             _secure = true
         } else {
@@ -380,7 +380,7 @@
     /// - Parameter headerFields: The response header fields to check for cookies.
     /// - Parameter URL: The URL that the cookies came from - relevant to how the cookies are interpeted.
     /// - Returns: An array of NSHTTPCookie objects
-    open class func cookies(withResponseHeaderFields headerFields: [String : String], forURL url: URL) -> [HTTPCookie] {
+    open class func cookies(withResponseHeaderFields headerFields: [String : String], for URL: URL) -> [HTTPCookie] {
 
         //HTTP Cookie parsing based on RFC 6265: https://tools.ietf.org/html/rfc6265
         //Though RFC6265 suggests that multiple cookies cannot be folded into a single Set-Cookie field, this is
@@ -405,7 +405,7 @@
         //bake the cookies
         var httpCookies: [HTTPCookie] = []
         for i in 0..<cookieIndices.count-1 {
-            if let aCookie = createHttpCookie(url: url, pairs: nameValuePairs[cookieIndices[i]..<cookieIndices[i+1]]) {
+            if let aCookie = createHttpCookie(url: URL, pairs: nameValuePairs[cookieIndices[i]..<cookieIndices[i+1]]) {
                 httpCookies.append(aCookie)
             }
         }
diff --git a/Foundation/NSHTTPCookieStorage.swift b/Foundation/NSHTTPCookieStorage.swift
index 2746fad..854401e 100644
--- a/Foundation/NSHTTPCookieStorage.swift
+++ b/Foundation/NSHTTPCookieStorage.swift
@@ -128,7 +128,7 @@
       @param sortOrder an array of NSSortDescriptors which represent the preferred sort order of the resulting array.
       @discussion proper sorting of cookies may require extensive string conversion, which can be avoided by allowing the system to perform the sorting.  This API is to be preferred over the more generic -[NSHTTPCookieStorage cookies] API, if sorting is going to be performed.
     */
-    open func sortedCookies(using sortOrder: [SortDescriptor]) -> [HTTPCookie] { NSUnimplemented() }
+    open func sortedCookies(using sortOrder: [NSSortDescriptor]) -> [HTTPCookie] { NSUnimplemented() }
 }
 
 public extension Notification.Name {
diff --git a/Foundation/NSIndexSet.swift b/Foundation/NSIndexSet.swift
index 7b0cf52..6c5490d 100644
--- a/Foundation/NSIndexSet.swift
+++ b/Foundation/NSIndexSet.swift
@@ -133,7 +133,7 @@
         return _ranges.first?.location ?? NSNotFound
     }
     open var lastIndex: Int {
-        guard _ranges.count > 0 else {
+        guard !_ranges.isEmpty else {
             return NSNotFound
         }
         return NSMaxRange(_ranges.last!) - 1
@@ -557,7 +557,7 @@
     
     internal func _mergeOverlappingRangesStartingAtIndex(_ index: Int) {
         var rangeIndex = index
-        while _ranges.count > 0 && rangeIndex < _ranges.count - 1 {
+        while !_ranges.isEmpty && rangeIndex < _ranges.count - 1 {
             let curRange = _ranges[rangeIndex]
             let nextRange = _ranges[rangeIndex + 1]
             let curEnd = NSMaxRange(curRange)
diff --git a/Foundation/NSJSONSerialization.swift b/Foundation/NSJSONSerialization.swift
index 3d6d607..8b97994 100644
--- a/Foundation/NSJSONSerialization.swift
+++ b/Foundation/NSJSONSerialization.swift
@@ -157,7 +157,6 @@
     /* Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil.
        The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
      */
-    /// - Experiment: Note that the return type of this function is different than on Darwin Foundation (Any instead of AnyObject). This is likely to change once we have a more complete story for bridging in place.
     open class func jsonObject(with data: Data, options opt: ReadingOptions = []) throws -> Any {
         return try data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Any in
             let encoding: String.Encoding
diff --git a/Foundation/NSKeyedArchiver.swift b/Foundation/NSKeyedArchiver.swift
index e4298b4..45a8028 100644
--- a/Foundation/NSKeyedArchiver.swift
+++ b/Foundation/NSKeyedArchiver.swift
@@ -9,7 +9,9 @@
 
 import CoreFoundation
 
-// Archives created using the class method archivedRootDataWithObject used this key for the root object in the hierarchy of encoded objects. The NSKeyedUnarchiver class method unarchiveObjectWithData: will look for this root key as well. You can also use it as the key for the root object in your own archives.
+/// Archives created using the class method `archivedData(withRootObject:)` use this key
+/// for the root object in the hierarchy of encoded objects. The `NSKeyedUnarchiver` class method
+/// `unarchiveObject(with:)` looks for this root key as well.
 public let NSKeyedArchiveRootObjectKey: String = "root"
 
 internal let NSKeyedArchiveNullObjectReference = _NSKeyedArchiverUID(value: 0)
@@ -34,7 +36,29 @@
         NSNumber.self
 ]
 
+/// `NSKeyedArchiver`, a concrete subclass of `NSCoder`, provides a way to encode objects
+/// (and scalar values) into an architecture-independent format that can be stored in a file.
+/// When you archive a set of objects, the class information and instance variables for each object
+/// are written to the archive. `NSKeyedArchiver`’s companion class, `NSKeyedUnarchiver`,
+/// decodes the data in an archive and creates a set of objects equivalent to the original set.
+///
+/// A keyed archive differs from a non-keyed archive in that all the objects and values
+/// encoded into the archive are given names, or keys. When decoding a non-keyed archive,
+/// values have to be decoded in the same order in which they were encoded.
+/// When decoding a keyed archive, because values are requested by name, values can be decoded
+/// out of sequence or not at all. Keyed archives, therefore, provide better support
+/// for forward and backward compatibility.
+/// 
+/// The keys given to encoded values must be unique only within the scope of the current
+/// object being encoded. A keyed archive is hierarchical, so the keys used by object A
+/// to encode its instance variables do not conflict with the keys used by object B,
+/// even if A and B are instances of the same class. Within a single object,
+/// however, the keys used by a subclass can conflict with keys used in its superclasses.
+///
+/// An `NSKeyedArchiver` object can write the archive data to a file or to a
+/// mutable-data object (an instance of `NSMutableData`) that you provide.
 open class NSKeyedArchiver : NSCoder {
+
     struct ArchiverFlags : OptionSet {
         let rawValue : UInt
         
@@ -67,7 +91,12 @@
     private var _classes : Dictionary<String, _NSKeyedArchiverUID> = [:]
     private var _cache : Array<_NSKeyedArchiverUID> = []
 
+    /// The archiver’s delegate.
     open weak var delegate: NSKeyedArchiverDelegate?
+    
+    /// The format in which the receiver encodes its data.
+    ///
+    /// The available formats are `xml` and `binary`.
     open var outputFormat = PropertyListSerialization.PropertyListFormat.binary {
         willSet {
             if outputFormat != PropertyListSerialization.PropertyListFormat.xml &&
@@ -77,6 +106,13 @@
         }
     }
     
+    /// Returns an `NSData` object containing the encoded form of the object graph
+    /// whose root object is given.
+    ///
+    /// - Parameter rootObject: The root of the object graph to archive.
+    /// - Returns:              An `NSData` object containing the encoded form of the object graph
+    ///                         whose root object is rootObject. The format of the archive is
+    ///                         `NSPropertyListBinaryFormat_v1_0`.
     open class func archivedData(withRootObject rootObject: Any) -> Data {
         let data = NSMutableData()
         let keyedArchiver = NSKeyedArchiver(forWritingWith: data)
@@ -87,6 +123,14 @@
         return data._swiftObject
     }
     
+    /// Archives an object graph rooted at a given object by encoding it into a data object
+    /// then atomically writes the resulting data object to a file at a given path,
+    /// and returns a Boolean value that indicates whether the operation was successful.
+    ///
+    /// - Parameters:
+    ///   - rootObject: The root of the object graph to archive.
+    ///   - path:       The path of the file in which to write the archive.
+    /// - Returns:      `true` if the operation was successful, otherwise `false`.
     open class func archiveRootObject(_ rootObject: Any, toFile path: String) -> Bool {
         var fd : Int32 = -1
         var auxFilePath : String
@@ -126,8 +170,8 @@
         return finishedEncoding
     }
     
-    public override init() {
-        NSUnimplemented()
+    public override convenience init() {
+        self.init(forWritingWith: NSMutableData())
     }
     
     private init(output: AnyObject) {
@@ -135,6 +179,12 @@
         super.init()
     }
     
+    /// Returns the archiver, initialized for encoding an archive into a given a mutable-data object.
+    ///
+    /// When you finish encoding data, you must invoke `finishEncoding()` at which point data
+    /// is filled. The format of the archive is `NSPropertyListBinaryFormat_v1_0`.
+    ///
+    /// - Parameter data: The mutable-data object into which the archive is written.
     public convenience init(forWritingWith data: NSMutableData) {
         self.init(output: data)
     }
@@ -162,12 +212,24 @@
         return __CFBinaryPlistWriteToStream(plist, self._stream) > 0
     }
     
-    
-    /// If encoding has not yet finished, then invoking this property will call finishEncoding and return the data. If you initialized the keyed archiver with a specific mutable data instance, then it will be returned from this property after finishEncoding is called.
+    /// Returns the encoded data for the archiver.
+    ///
+    /// If encoding has not yet finished, invoking this property calls `finishEncoding()`
+    /// and returns the data. If you initialized the keyed archiver with a specific
+    /// mutable data instance, then that data is returned by the property after
+    /// `finishEncoding()` is called.
     open var encodedData: Data {
-        NSUnimplemented()
+        
+        if !_flags.contains(.finishedEncoding) {
+            finishEncoding()
+        }
+        
+        return (_stream as! NSData)._swiftObject
     }
 
+    /// Instructs the archiver to construct the final data stream.
+    ///
+    /// No more values can be encoded after this method is called. You must call this method when finished.
     open func finishEncoding() {
         if _flags.contains(ArchiverFlags.finishedEncoding) {
             return
@@ -204,6 +266,15 @@
         }
     }
 
+    /// Adds a class translation mapping to `NSKeyedArchiver` whereby instances of a given
+    /// class are encoded with a given class name instead of their real class names.
+    ///
+    /// When encoding, the class’s translation mapping is used only if no translation
+    /// is found first in an instance’s separate translation map.
+    ///
+    /// - Parameters:
+    ///   - codedName:  The name of the class that `NSKeyedArchiver` uses in place of `cls`.
+    ///   - cls:        The class for which to set up a translation mapping.
     open class func setClassName(_ codedName: String?, for cls: AnyClass) {
         let clsName = String(describing: type(of: cls))
         _classNameMapLock.synchronized {
@@ -211,6 +282,15 @@
         }
     }
     
+    /// Adds a class translation mapping to `NSKeyedArchiver` whereby instances of a given
+    /// class are encoded with a given class name instead of their real class names.
+    ///
+    /// When encoding, the receiver’s translation map overrides any translation
+    /// that may also be present in the class’s map.
+    ///
+    /// - Parameters:
+    ///   - codedName:  The name of the class that the archiver uses in place of `cls`.
+    ///   - cls:        The class for which to set up a translation mapping.
     open func setClassName(_ codedName: String?, for cls: AnyClass) {
         let clsName = String(describing: type(of: cls))
         _classNameMap[clsName] = codedName
@@ -428,7 +508,7 @@
             
             if let ns = clsv as? NSObject.Type {
                 let classHints = ns.classFallbacksForKeyedArchiver()
-                if classHints.count > 0 {
+                if !classHints.isEmpty {
                     classDict["$classhints"] = classHints
                 }
             }
@@ -478,10 +558,10 @@
             return objectToEncode
         }
         
-        // object replaced by NSObject.replacementObjectForKeyedArchiver
+        // object replaced by NSObject.replacementObject(for:)
         // if it is replaced with nil, it cannot be further replaced
         if let ns = objectToEncode as? NSObject {
-            objectToEncode = ns.replacementObjectForKeyedArchiver(self)
+            objectToEncode = ns.replacementObject(for: self)
             if objectToEncode == nil {
                 replaceObject(object!, withObject: nil)
                 return nil
@@ -576,10 +656,21 @@
         _encodeObject(object, forKey: nil, conditional: true)
     }
 
+    /// Encodes a given object and associates it with a given key.
+    ///
+    /// - Parameters:
+    ///   - objv:   The value to encode.
+    ///   - key:    The key with which to associate `objv`.
     open override func encode(_ objv: Any?, forKey key: String) {
         _encodeObject(objv, forKey: key, conditional: false)
     }
     
+    /// Encodes a reference to a given object and associates it with a given key
+    /// only if it has been unconditionally encoded elsewhere in the archive with `encode(_:forKey:)`.
+    ///
+    /// - Parameters:
+    ///   - objv:   The object to encode.
+    ///   - key:    The key with which to associate the encoded value.
     open override func encodeConditionalObject(_ objv: Any?, forKey key: String) {
         _encodeObject(objv, forKey: key, conditional: true)
     }
@@ -678,27 +769,57 @@
         }
     }
 
+    /// Encodes a given Boolean value and associates it with a given key.
+    ///
+    /// - Parameters:
+    ///   - boolv:  The value to encode.
+    ///   - key:    The key with which to associate `boolv`.
     open override func encode(_ boolv: Bool, forKey key: String) {
         _encodeValue(NSNumber(value: boolv), forKey: key)
     }
     
 
+    /// Encodes a given 32-bit integer value and associates it with a given key.
+    ///
+    /// - Parameters:
+    ///   - intv:   The value to encode.
+    ///   - key:    The key with which to associate `intv`.
     open override func encode(_ intv: Int32, forKey key: String) {
         _encodeValue(NSNumber(value: intv), forKey: key)
     }
     
+    /// Encodes a given 64-bit integer value and associates it with a given key.
+    ///
+    /// - Parameters:
+    ///   - intv:   The value to encode.
+    ///   - key:    The key with which to associate `intv`.
     open override func encode(_ intv: Int64, forKey key: String) {
         _encodeValue(NSNumber(value: intv), forKey: key)
     }
     
+    /// Encodes a given float value and associates it with a given key.
+    ///
+    /// - Parameters:
+    ///   - realv:  The value to encode.
+    ///   - key:    The key with which to associate `realv`.
     open override func encode(_ realv: Float, forKey key: String) {
         _encodeValue(NSNumber(value: realv), forKey: key)
     }
     
+    /// Encodes a given double value and associates it with a given key.
+    ///
+    /// - Parameters:
+    ///   - realv:  The value to encode.
+    ///   - key:    The key with which to associate `realv`.
     open override func encode(_ realv: Double, forKey key: String) {
         _encodeValue(NSNumber(value: realv), forKey: key)
     }
     
+    /// Encodes a given integer value and associates it with a given key.
+    ///
+    /// - Parameters:
+    ///   - intv:   The value to encode.
+    ///   - key:    The key with which to associate `intv`.
     open override func encode(_ intv: Int, forKey key: String) {
         _encodeValue(NSNumber(value: intv), forKey: key)
     }
@@ -708,6 +829,13 @@
         encode(data._nsObject)
     }
     
+    /// Encodes a given number of bytes from a given C array of bytes and associates
+    /// them with the a given key.
+    ///
+    /// - Parameters:
+    ///   - bytesp: A C array of bytes to encode.
+    ///   - lenv:   The number of bytes from `bytesp` to encode.
+    ///   - key:    The key with which to associate the encoded value.
     open override func encodeBytes(_ bytesp: UnsafePointer<UInt8>?, length lenv: Int, forKey key: String) {
         // this encodes the data inline
         let data = NSData(bytes: bytesp, length: lenv)
@@ -732,14 +860,10 @@
         _encodeValue(objectRefs._bridgeToObjectiveC(), forKey: key)
     }
     
-    /**
-        Enables secure coding support on this keyed archiver. You do not need to enable
-        secure coding on the archiver to enable secure coding on the unarchiver. Enabling
-        secure coding on the archiver is a way for you to be sure that all classes that
-        are encoded conform with NSSecureCoding (it will throw an exception if a class
-        which does not NSSecureCoding is archived). Note that the getter is on the superclass,
-        NSCoder. See NSCoder for more information about secure coding.
-     */
+    /// Indicates whether the archiver requires all archived classes to conform to `NSSecureCoding`.
+    ///
+    /// If you set the receiver to require secure coding, it will cause a fatal error
+    /// if you attempt to archive a class which does not conform to `NSSecureCoding`.
     open override var requiresSecureCoding: Bool {
         get {
             return _flags.contains(ArchiverFlags.requiresSecureCoding)
@@ -753,8 +877,11 @@
         }
     }
     
-    // During encoding, the coder first checks with the coder's
-    // own table, then if there was no mapping there, the class's.
+    /// Returns the class name with which `NSKeyedArchiver` encodes instances of a given class.
+    ///
+    /// - Parameter cls:    The class for which to determine the translation mapping.
+    /// - Returns:          The class name with which `NSKeyedArchiver` encodes instances of `cls`.
+    ///                     Returns `nil` if `NSKeyedArchiver` does not have a translation mapping for `cls`.
     open class func classNameForClass(_ cls: AnyClass) -> String? {
         let clsName = String(reflecting: cls)
         var mappedClass : String?
@@ -766,6 +893,12 @@
         return mappedClass
     }
     
+    /// Returns the class name with which the archiver encodes instances of a given class.
+    ///
+    /// - Parameter cls:    The class for which to determine the translation mapping.
+    /// - Returns:          The class name with which the receiver encodes instances of cls.
+    ///                     Returns `nil` if the archiver does not have a translation
+    ///                     mapping for `cls`. The class’s separate translation map is not searched.
     open func classNameForClass(_ cls: AnyClass) -> String? {
         let clsName = String(reflecting: cls)
         return _classNameMap[clsName]
@@ -788,34 +921,62 @@
 
 }
 
+/// The `NSKeyedArchiverDelegate` protocol defines the optional methods implemented
+/// by delegates of `NSKeyedArchiver` objects.
 public protocol NSKeyedArchiverDelegate : class {
     
-    // Informs the delegate that the object is about to be encoded.  The delegate
-    // either returns this object or can return a different object to be encoded
-    // instead.  The delegate can also fiddle with the coder state.  If the delegate
-    // returns nil, nil is encoded.  This method is called after the original object
-    // may have replaced itself with replacementObjectForKeyedArchiver:.
-    // This method is not called for an object once a replacement mapping has been
-    // setup for that object (either explicitly, or because the object has previously
-    // been encoded).  This is also not called when nil is about to be encoded.
-    // This method is called whether or not the object is being encoded conditionally.
+    /// Informs the delegate that `object` is about to be encoded.
+    ///
+    /// This method is called after the original object may have replaced itself
+    /// with `replacementObject(for:)`.
+    ///
+    /// This method is called whether or not the object is being encoded conditionally.
+    ///
+    /// This method is not called for an object once a replacement mapping has been set up
+    /// for that object (either explicitly, or because the object has previously been encoded).
+    /// This method is also not called when `nil` is about to be encoded.
+    ///
+    /// - Parameters:
+    ///   - archiver:   The archiver that invoked the method.
+    ///   - object:     The object that is about to be encoded.
+    /// - Returns:      Either object or a different object to be encoded in its stead.
+    ///                 The delegate can also modify the coder state. If the delegate
+    ///                 returns `nil`, `nil` is encoded.
     func archiver(_ archiver: NSKeyedArchiver, willEncode object: Any) -> Any?
     
-    // Informs the delegate that the given object has been encoded.  The delegate
-    // might restore some state it had fiddled previously, or use this to keep
-    // track of the objects which are encoded.  The object may be nil.  Not called
-    // for conditional objects until they are really encoded (if ever).
+    /// Informs the delegate that a given object has been encoded.
+    ///
+    /// The delegate might restore some state it had modified previously,
+    /// or use this opportunity to keep track of the objects that are encoded.
+    ///
+    /// This method is not called for conditional objects until they are actually encoded (if ever).
+    ///
+    /// - Parameters:
+    ///   - archiver:   The archiver that invoked the method.
+    ///   - object:     The object that has been encoded.
     func archiver(_ archiver: NSKeyedArchiver, didEncode object: Any?)
     
-    // Informs the delegate that the newObject is being substituted for the
-    // object. This is also called when the delegate itself is doing/has done
-    // the substitution. The delegate may use this method if it is keeping track
-    // of the encoded or decoded objects.
+    /// Informs the delegate that one given object is being substituted for another given object.
+    ///
+    /// This method is called even when the delegate itself is doing, or has done,
+    /// the substitution. The delegate may use this method if it is keeping track
+    /// of the encoded or decoded objects.
+    ///
+    /// - Parameters:
+    ///   - archiver:   The archiver that invoked the method.
+    ///   - object:     The object being replaced in the archive.
+    ///   - newObject:  The object replacing `object` in the archive.
     func archiver(_ archiver: NSKeyedArchiver, willReplace object: Any?, withObject newObject: Any?)
     
-    // Notifies the delegate that encoding is about to finish.
+
+    /// Notifies the delegate that encoding is about to finish.
+    ///
+    /// - Parameter archiver: The archiver that invoked the method.
     func archiverWillFinish(_ archiver: NSKeyedArchiver)
     
-    // Notifies the delegate that encoding has finished.
+
+    /// Notifies the delegate that encoding has finished.
+    ///
+    /// - Parameter archiver: The archiver that invoked the method.
     func archiverDidFinish(_ archiver: NSKeyedArchiver)
 }
diff --git a/Foundation/NSKeyedUnarchiver.swift b/Foundation/NSKeyedUnarchiver.swift
index 383b9f8..bc97d23 100644
--- a/Foundation/NSKeyedUnarchiver.swift
+++ b/Foundation/NSKeyedUnarchiver.swift
@@ -51,7 +51,7 @@
     private var _classes : Dictionary<UInt32, AnyClass> = [:]
     private var _cache : Array<_NSKeyedArchiverUID> = []
     private var _allowedClasses : Array<[AnyClass]> = []
-    private var _error : NSError? = nil
+    private var _error : Error? = nil
     
     override open var error: Error? {
         return _error
@@ -96,9 +96,9 @@
         
         do {
             try _readPropertyList()
-        } catch let error as NSError {
-            failWithError(error)
         } catch {
+            failWithError(error)
+            self._error = error
         }
     }
   
@@ -542,10 +542,9 @@
             try _decodeArrayOfObjectsForKey(key) { object in
                 array.append(object)
             }
-        } catch let error as NSError {
+        } catch {
             failWithError(error)
             self._error = error
-        } catch {
         }
         
         return array
@@ -607,10 +606,9 @@
     open override func decodeObject(forKey key: String) -> Any? {
         do {
             return try _decodeObject(forKey: key)
-        } catch let error as NSError {
+        } catch {
             failWithError(error)
             self._error = error
-        } catch {
         }
         return nil
     }
@@ -623,10 +621,9 @@
                 defer { self._allowedClasses.removeLast() }
                 
                 return try _decodeObject(forKey: key)
-            } catch let error as NSError {
+            } catch {
                 failWithError(error)
                 self._error = error
-            } catch {
             }
         }        
         return nil
@@ -660,10 +657,9 @@
     open override func decodeObject() -> Any? {
         do {
             return try _decodeObject(forKey: nil)
-        } catch let error as NSError {
+        } catch {
             failWithError(error)
             self._error = error
-        } catch {
         }
         
         return nil
@@ -673,12 +669,12 @@
         return _decodeObject(of: NSPropertyListClasses)
     }
     
-    open override func decodePropertyListForKey(_ key: String) -> Any? {
+    open override func decodePropertyList(forKey key: String) -> Any? {
         return decodeObject(of: NSPropertyListClasses, forKey:key)
     }
     
     /**
-        Note that unlike decodePropertyListForKey(), _decodePropertyListForKey() decodes
+        Note that unlike decodePropertyList(forKey:), _decodePropertyListForKey() decodes
         a property list in the current decoding context rather than as an object. It's
         also able to return value types.
      */
@@ -867,15 +863,9 @@
     }
 
     open class func unarchiveTopLevelObjectWithData(_ data: Data) throws -> Any? {
-        var root : Any? = nil
-        
         let keyedUnarchiver = NSKeyedUnarchiver(forReadingWithData: data)
-        do {
-            try root = keyedUnarchiver.decodeTopLevelObject(forKey: NSKeyedArchiveRootObjectKey)
-            keyedUnarchiver.finishDecoding()
-        } catch {
-        }
-        
+        let root = try keyedUnarchiver.decodeTopLevelObject(forKey: NSKeyedArchiveRootObjectKey)
+        keyedUnarchiver.finishDecoding()
         return root
     }
 }
diff --git a/Foundation/NSLocale.swift b/Foundation/NSLocale.swift
index e18b10f..f556df2 100644
--- a/Foundation/NSLocale.swift
+++ b/Foundation/NSLocale.swift
@@ -27,7 +27,7 @@
         return unsafeBitCast(self, to: CFType.self)
     }
     
-    open func object(forKey key: NSLocale.Key) -> AnyObject? {
+    open func object(forKey key: NSLocale.Key) -> Any? {
         return CFLocaleGetValue(_cfObject, key.rawValue._cfObject)
     }
     
diff --git a/Foundation/NSNotification.swift b/Foundation/NSNotification.swift
index 9c82cb1..291b290 100644
--- a/Foundation/NSNotification.swift
+++ b/Foundation/NSNotification.swift
@@ -167,12 +167,12 @@
         }
     }
 
-    open func post(name aName: Notification.Name, object anObject: AnyObject?, userInfo aUserInfo: [AnyHashable : Any]? = nil) {
+    open func post(name aName: Notification.Name, object anObject: Any?, userInfo aUserInfo: [AnyHashable : Any]? = nil) {
         let notification = Notification(name: aName, object: anObject, userInfo: aUserInfo)
         post(notification)
     }
 
-    open func removeObserver(_ observer: AnyObject) {
+    open func removeObserver(_ observer: Any) {
         removeObserver(observer, name: nil, object: nil)
     }
 
diff --git a/Foundation/NSObject.swift b/Foundation/NSObject.swift
index 9bb2e53..4b8a58a 100644
--- a/Foundation/NSObject.swift
+++ b/Foundation/NSObject.swift
@@ -7,30 +7,78 @@
 // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
 //
 
-
 import CoreFoundation
 
-public protocol NSObjectProtocol: class {
+/// The `NSObjectProtocol` groups methods that are fundamental to all Foundation objects.
+///
+/// If an object conforms to this protocol, it can be considered a first-class object.
+/// 
+/// The Cocoa root class, NSObject, adopts this protocol, so all objects inheriting
+/// from NSObject have the features described by this protocol.
+public protocol NSObjectProtocol : class {
     
+    /// Returns a Boolean value that indicates whether the instance
+    /// and a given `object` are equal.
+    ///
+    /// This method defines what it means for instances to be equal. For example, a container
+    /// object might define two containers as equal if their corresponding objects all respond
+    /// true to an `isEqual(_:)` request. See the `NSData`, `NSDictionary`, `NSArray`,
+    /// and `NSString` class specifications for examples of the use of this method.
+    ///
+    /// If two objects are equal, they must have the same hash value.
+    /// This last point is particularly important if you define `isEqual(_:)` in a subclass
+    /// and intend to put instances of that subclass into a collection.
+    /// Make sure you also define hash in your subclass.
+    ///
+    /// - Parameter object: The object to be compared to the instance.
+    ///                     May be `nil`, in which case this method returns `false`.
+    /// - Returns:          `true` if the instance and `object` are equal, otherwise `false`.
     func isEqual(_ object: Any?) -> Bool
+    
+    /// Returns an integer that can be used as a table address in a hash table structure.
+    /// 
+    /// If two objects are equal (as determined by the `isEqual(_:)` method),
+    /// they must have the same hash value. This last point is particularly important
+    /// if you define `hash` in a subclass and intend to put instances of that subclass
+    /// into a collection.
+    ///
+    /// If a mutable object is added to a collection that uses hash values to determine
+    /// the object’s position in the collection, the value returned by the `hash` property
+    /// of the object must not change while the object is in the collection. Therefore, either
+    /// the `hash` property must not rely on any of the object’s internal state information
+    /// or you must make sure the object’s internal state information does not change while
+    /// the object is in the collection. Thus, for example, a mutable dictionary can be put
+    /// in a hash table but you must not change it while it is in there.
+    /// (Note that it can be difficult to know whether or not a given object is in a collection.)
     var hash: Int { get }
     
+    /// Returns the instance itself.
+    ///
+    /// - Returns: The instance itself.
     func `self`() -> Self
     
+    /// Returns a Boolean value that indicates whether the instance does not descend from NSObject.
+    ///
+    /// - Returns: `false` if the instance really descends from `NSObject`, otherwise `true`.
     func isProxy() -> Bool
 
+    /// Returns a string that describes the contents of the instance.
     var description: String { get }
     
+    /// Returns a string that describes the contents of the instance for presentation
+    /// in the debugger.
     var debugDescription: String { get }
 }
 
 extension NSObjectProtocol {
+    
     public var debugDescription: String {
         return description
     }
 }
 
 public struct NSZone : ExpressibleByNilLiteral {
+    
     public init() {
         
     }
@@ -40,35 +88,76 @@
     }
 }
 
+/// The `NSCopying` protocol declares a method for providing functional copies of an object.
+/// The exact meaning of “copy” can vary from class to class, but a copy must be a functionally
+/// independent object with values identical to the original at the time the copy was made.
+///
+/// NSCopying declares one method, `copy(with:)`, but copying is commonly invoked with the
+/// convenience method `copy`. The copy method is defined for all objects inheriting from NSObject
+/// and simply invokes `copy(with:)` with the `nil` zone.
+///
+/// If a subclass inherits `NSCopying` from its superclass and declares additional instance variables,
+/// the subclass has to override `copy(with:)` to properly handle its own instance variables,
+/// invoking the superclass’s implementation first.
 public protocol NSCopying {
     
+    /// Returns a new instance that’s a copy of the current one.
+    ///
+    /// - Parameter zone:   This parameter is ignored. Memory zones are no longer used.
+    /// - Returns:          A new instance that’s a copy of the current one.
     func copy(with zone: NSZone?) -> Any
 }
 
 extension NSCopying {
+    
+    /// Returns a new instance that’s a copy of the current one.
+    ///
+    /// - Returns: A new instance that’s a copy of the current one.
     public func copy() -> Any {
         return copy(with: nil)
     }
 }
 
+/// The `NSMutableCopying` protocol declares a method for providing mutable
+/// copies of an object. Only classes that define an “immutable vs. mutable” distinction
+/// should adopt this protocol. Classes that don’t define such a distinction should
+/// adopt `NSCopying` instead.
 public protocol NSMutableCopying {
     
+    /// Returns a new instance that’s a mutable copy of the current one.
+    ///
+    /// - Parameter zone:   This parameter is ignored. Memory zones are no longer used.
+    /// - Returns:          A new instance that’s a mutable copy of the current one.
     func mutableCopy(with zone: NSZone?) -> Any
 }
 
 extension NSMutableCopying {
+    
+    /// Returns a new instance that’s a mutable copy of the current one.
+    ///
+    /// - Returns: A new instance that’s a mutable copy of the current one.
     public func mutableCopy() -> Any {
         return mutableCopy(with: nil)
     }
 }
 
+/// The root class of most Foundation class hierarchies.
 open class NSObject : NSObjectProtocol, Equatable, Hashable {
     // Important: add no ivars here. It will subvert the careful layout of subclasses that bridge into CF.    
     
-    public init() {
-        
-    }
+    /// Implemented by subclasses to initialize a new object immediately after memory
+    /// for it has been allocated.
+    public init() {}
     
+    /// Returns the object returned by `copy(with:)`.
+    ///
+    /// This is a convenience method for classes that adopt the `NSCopying` protocol.
+    /// `NSObject` does not itself support the `NSCopying` protocol.
+    /// Subclasses must support the protocol and implement the `copy(with:)` method.
+    /// A subclass version of the `copy(with:)` method should invoke `super`'s method first,
+    /// to incorporate its implementation, unless the subclass descends directly from `NSObject`.
+    ///
+    /// - Returns: The object returned by the `NSCopying` protocol method `copy(with:)`.
     open func copy() -> Any {
         if let copyable = self as? NSCopying {
             return copyable.copy(with: nil)
@@ -76,6 +165,12 @@
         return self
     }
     
+    /// Returns the object returned by `mutableCopy(with:)` where the zone is `nil.`
+    ///
+    /// This is a convenience method for classes that adopt the `NSMutableCopying` protocol.
+    ///
+    /// - Returns: The object returned by the `NSMutableCopying` protocol method
+    ///            `mutableCopy(with:)`, where the zone is `nil`.
     open func mutableCopy() -> Any {
         if let copyable = self as? NSMutableCopying {
             return copyable.mutableCopy(with: nil)
@@ -83,6 +178,13 @@
         return self
     }
     
+    /// Returns a Boolean value that indicates whether the instance is equal to another given object.
+    ///
+    /// The default implementation for this method provided by `NSObject` returns `true` if
+    /// the objects being compared refer to the same instance.
+    ///
+    /// - Parameter object: The object with which to compare the instance.
+    /// - Returns:          `true` if the instance is equal to `object`, otherwise `false`.
     open func isEqual(_ object: Any?) -> Bool {
         if let obj = object as? NSObject {
             return obj === self
@@ -90,22 +192,46 @@
         return false
     }
     
+    /// Returns an integer that can be used as a table address in a hash table structure.
+    ///
+    /// If two objects are equal (as determined by the `isEqual(_:)` method),
+    /// they must have the same hash value. This last point is particularly important
+    /// if you define `hash` in a subclass and intend to put instances of that subclass
+    /// into a collection.
+    ///
+    /// If a mutable object is added to a collection that uses hash values to determine
+    /// the object’s position in the collection, the value returned by the `hash` property
+    /// of the object must not change while the object is in the collection. Therefore, either
+    /// the `hash` property must not rely on any of the object’s internal state information
+    /// or you must make sure the object’s internal state information does not change while
+    /// the object is in the collection. Thus, for example, a mutable dictionary can be put
+    /// in a hash table but you must not change it while it is in there.
+    /// (Note that it can be difficult to know whether or not a given object is in a collection.)
     open var hash: Int {
         return ObjectIdentifier(self).hashValue
     }
     
+    /// Returns the instance itself.
+    ///
+    /// - Returns: The instance itself.
     open func `self`() -> Self {
         return self
     }
     
+    /// Returns a Boolean value that indicates whether the instance does not descend from NSObject.
+    ///
+    /// - Returns: `false` if the instance really descends from `NSObject`, otherwise `true`.
     open func isProxy() -> Bool {
         return false
     }
     
+    /// Returns a string that describes the contents of the instance.
     open var description: String {
         return "<\(type(of: self)): \(Unmanaged.passUnretained(self).toOpaque())>"
     }
     
+    /// Returns a string that describes the contents of the instance for presentation
+    /// in the debugger.
     open var debugDescription: String {
         return description
     }
@@ -114,46 +240,82 @@
         return 0
     }
     
-    // TODO move these back into extensions once extension methods can be overriden
+    // TODO: move these back into extensions once extension methods can be overriden
+    
+    /// Overridden by subclasses to substitute a class other than its own during coding.
+    ///
+    /// This property is needed for `NSCoder`.
+    /// `NSObject`’s implementation returns the instance's class.
+    /// The private subclasses of a class cluster substitute the name of their public
+    /// superclass when being archived.
     open var classForCoder: AnyClass {
         return type(of: self)
     }
  
-    open func replacementObjectForCoder(_ aCoder: NSCoder) -> AnyObject? {
+    /// Overridden by subclasses to substitute another object for itself during encoding.
+    ///
+    /// An object might encode itself into an archive, but encode a proxy for itself if
+    /// it’s being encoded for distribution. This method is invoked by `NSCoder`.
+    /// `NSObject`’s implementation returns `self`.
+    ///
+    /// - Parameter aCoder: The coder encoding the instance.
+    /// - Returns:          The object encode instead of the instance (if different).
+    open func replacementObject(for aCoder: NSCoder) -> Any? {
         return self
     }
 
-    // TODO: Could perhaps be an extension of NSCoding instead. The reason it is an extension of NSObject is the lack of default implementations on protocols in Objective-C.
+    // TODO: Could perhaps be an extension of NSCoding instead.
+    // The reason it is an extension of NSObject is the lack of default
+    // implementations on protocols in Objective-C.
+    
+    /// Subclasses to substitute a new class for instances during keyed archiving.
+    ///
+    /// The object will be encoded as if it were a member of the class. This property is
+    /// overridden by the encoder class and instance name to class encoding tables.
+    /// If this property is `nil`, the result of this property is ignored.
     open var classForKeyedArchiver: AnyClass? {
         return self.classForCoder
     }
     
-    // Implemented by classes to substitute a new class for instances during
-    // encoding.  The object will be encoded as if it were a member of the
-    // returned class.  The results of this method are overridden by the archiver
-    // class and instance name<->class encoding tables.  If nil is returned,
-    // then the null object is encoded.  This method returns the result of
-    // [self classForArchiver] by default, NOT -classForCoder as might be
-    // expected.  This is a concession to source compatibility.
-    
-    open func replacementObjectForKeyedArchiver(_ archiver: NSKeyedArchiver) -> AnyObject? {
-        return self.replacementObjectForCoder(archiver)
+    /// Overridden by subclasses to substitute another object for itself during keyed archiving.
+    ///
+    /// This method is called only if no replacement mapping for the object has been set up
+    /// in the encoder (for example, due to a previous call of `replacementObject(for:)` to that object).
+    ///
+    /// - Parameter archiver:   A keyed archiver creating an archive.
+    /// - Returns:              The object encode instead of the instance (if different).
+    open func replacementObject(for archiver: NSKeyedArchiver) -> Any? {
+        return self.replacementObject(for: archiver as NSCoder)
     }
     
-    // Implemented by classes to substitute new instances for the receiving
-    // instance during encoding.  The returned object will be encoded instead
-    // of the receiver (if different).  This method is called only if no
-    // replacement mapping for the object has been set up in the archiver yet
-    // (for example, due to a previous call of replacementObjectForKeyedArchiver:
-    // to that object).  This method returns the result of
-    // [self replacementObjectForArchiver:nil] by default, NOT
-    // -replacementObjectForCoder: as might be expected.  This is a concession
-    // to source compatibility.
-    
+    /// Overridden to return the names of classes that can be used to decode
+    /// objects if their class is unavailable.
+    ///
+    /// `NSKeyedArchiver` calls this method and stores the result inside the archive.
+    /// If the actual class of an object doesn’t exist at the time of unarchiving,
+    /// `NSKeyedUnarchiver` goes through the stored list of classes and uses the first one
+    /// that does exists as a substitute class for decoding the object.
+    /// The default implementation of this method returns empty array.
+    ///
+    /// You can use this method if you introduce a new class into your application to provide
+    /// some backwards compatibility in case the archive will be read on a system that does not
+    /// have that class. Sometimes there may be another class which may work nearly as well as
+    /// a substitute for the new class, and the archive keys and archived state for the new class
+    /// can be carefully chosen (or compatibility written out) so that the object can be unarchived
+    /// as the substitute class if necessary.
+    ///
+    /// - Returns: An array of strings that specify the names of classes in preferred order for unarchiving.
     open class func classFallbacksForKeyedArchiver() -> [String] {
         return []
     }
 
+    /// Overridden by subclasses to substitute a new class during keyed unarchiving.
+    ///
+    /// During keyed unarchiving, instances of the class will be decoded as members
+    /// of the returned class. This method overrides the results of the decoder’s class
+    /// and instance name to class encoding tables.
+    ///
+    /// - Returns: The class to substitute for the current class during keyed unarchiving.
     open class func classForKeyedUnarchiver() -> AnyClass {
         return self
     }
@@ -163,6 +325,14 @@
     }
 }
 
+/// Returns a Boolean value indicating whether two values are equal.
+///
+/// Equality is the inverse of inequality. For any values `a` and `b`,
+/// `a == b` implies that `a != b` is `false`.
+///
+/// - Parameters:
+///   - lhs: A value to compare.
+///   - rhs: Another value to compare.
 public func ==(lhs: NSObject, rhs: NSObject) -> Bool {
     return lhs.isEqual(rhs)
 }
diff --git a/Foundation/NSOperation.swift b/Foundation/NSOperation.swift
index a9e1058..fcc9b38 100644
--- a/Foundation/NSOperation.swift
+++ b/Foundation/NSOperation.swift
@@ -258,19 +258,19 @@
     }
     
     mutating func dequeue() -> Operation? {
-        if veryHigh.count > 0 {
+        if !veryHigh.isEmpty {
             return veryHigh.remove(at: 0)
         }
-        if high.count > 0 {
+        if !high.isEmpty {
             return high.remove(at: 0)
         }
-        if normal.count > 0 {
+        if !normal.isEmpty {
             return normal.remove(at: 0)
         }
-        if low.count > 0 {
+        if !low.isEmpty {
             return low.remove(at: 0)
         }
-        if veryLow.count > 0 {
+        if !veryLow.isEmpty {
             return veryLow.remove(at: 0)
         }
         return nil
diff --git a/Foundation/NSPathUtilities.swift b/Foundation/NSPathUtilities.swift
index 95d1f1c..4590787 100644
--- a/Foundation/NSPathUtilities.swift
+++ b/Foundation/NSPathUtilities.swift
@@ -470,7 +470,7 @@
     }
     
     internal func _longestCommonPrefix(_ strings: [String], caseSensitive: Bool) -> String? {
-        guard strings.count > 0 else {
+        guard !strings.isEmpty else {
             return nil
         }
         
diff --git a/Foundation/NSPropertyList.swift b/Foundation/NSPropertyList.swift
index 4f837f0..6eda275 100644
--- a/Foundation/NSPropertyList.swift
+++ b/Foundation/NSPropertyList.swift
@@ -67,7 +67,6 @@
         }
     }
 
-    /// - Experiment: Note that the return type of this function is different than on Darwin Foundation (Any instead of AnyObject). This is likely to change once we have a more complete story for bridging in place.
     open class func propertyList(from data: Data, options opt: ReadOptions = [], format: UnsafeMutablePointer<PropertyListFormat>?) throws -> Any {
         var fmt = kCFPropertyListBinaryFormat_v1_0
         var error: Unmanaged<CFError>? = nil
diff --git a/Foundation/NSRunLoop.swift b/Foundation/NSRunLoop.swift
index 82f2cca..c2a9459 100644
--- a/Foundation/NSRunLoop.swift
+++ b/Foundation/NSRunLoop.swift
@@ -33,14 +33,14 @@
     public var hashValue: Int {
         return rawValue.hashValue
     }
-}
 
-public func ==(lhs: RunLoopMode, rhs: RunLoopMode) -> Bool {
-    return lhs.rawValue == rhs.rawValue
-}
+    public static func ==(_ lhs: RunLoopMode, _ rhs: RunLoopMode) -> Bool {
+        return lhs.rawValue == rhs.rawValue
+    }
 
-public func <(lhs: RunLoopMode, rhs: RunLoopMode) -> Bool {
-    return lhs.rawValue < rhs.rawValue
+    public static func <(_ lhs: RunLoopMode, _ rhs: RunLoopMode) -> Bool {
+        return lhs.rawValue < rhs.rawValue
+    }
 }
 
 
diff --git a/Foundation/NSSortDescriptor.swift b/Foundation/NSSortDescriptor.swift
index 2dfdef5..7a09d86 100644
--- a/Foundation/NSSortDescriptor.swift
+++ b/Foundation/NSSortDescriptor.swift
@@ -8,7 +8,7 @@
 //
 
 
-open class SortDescriptor: NSObject, NSSecureCoding, NSCopying {
+open class NSSortDescriptor: NSObject, NSSecureCoding, NSCopying {
     
     public required init?(coder aDecoder: NSCoder) {
         NSUnimplemented()
@@ -42,34 +42,34 @@
     
     open var comparator: Comparator { NSUnimplemented() }
     
-    open func compareObject(_ object1: AnyObject, toObject object2: AnyObject) -> ComparisonResult  { NSUnimplemented() }// primitive - override this method if you want to perform comparisons differently (not key based for example)
-    open var reversedSortDescriptor: AnyObject  { NSUnimplemented() } // primitive - override this method to return a sort descriptor instance with reversed sort order
+    open func compare(_ object1: Any, to object2: Any) -> ComparisonResult { NSUnimplemented() }// primitive - override this method if you want to perform comparisons differently (not key based for example)
+    open var reversedSortDescriptor: Any { NSUnimplemented() } // primitive - override this method to return a sort descriptor instance with reversed sort order
 }
 
 extension NSSet {
     
-    public func sortedArrayUsingDescriptors(_ sortDescriptors: [SortDescriptor]) -> [AnyObject] { NSUnimplemented() }// returns a new array by sorting the objects of the receiver
+    public func sortedArray(using sortDescriptors: [NSSortDescriptor]) -> [Any] { NSUnimplemented() }// returns a new array by sorting the objects of the receiver
 }
 
 extension NSArray {
     
-    public func sortedArrayUsingDescriptors(_ sortDescriptors: [SortDescriptor]) -> [AnyObject] { NSUnimplemented() }// returns a new array by sorting the objects of the receiver
+    public func sortedArray(using sortDescriptors: [NSSortDescriptor]) -> [Any] { NSUnimplemented() }// returns a new array by sorting the objects of the receiver
 }
 
 extension NSMutableArray {
     
-    public func sortUsingDescriptors(_ sortDescriptors: [SortDescriptor]) { NSUnimplemented() } // sorts the array itself
+    public func sort(using sortDescriptors: [NSSortDescriptor]) { NSUnimplemented() } // sorts the array itself
 }
 
 
 extension NSOrderedSet {
     
     // returns a new array by sorting the objects of the receiver
-    public func sortedArrayUsingDescriptors(_ sortDescriptors: [SortDescriptor]) -> [AnyObject] { NSUnimplemented() }
+    public func sortedArray(using sortDescriptors: [NSSortDescriptor]) -> [Any] { NSUnimplemented() }
 }
 
 extension NSMutableOrderedSet {
     
     // sorts the ordered set itself
-    public func sortUsingDescriptors(_ sortDescriptors: [SortDescriptor]) { NSUnimplemented() }
+    public func sort(using sortDescriptors: [NSSortDescriptor]) { NSUnimplemented() }
 }
diff --git a/Foundation/NSStream.swift b/Foundation/NSStream.swift
index dbffd2c..4e22f37 100644
--- a/Foundation/NSStream.swift
+++ b/Foundation/NSStream.swift
@@ -110,7 +110,7 @@
         NSRequiresConcreteImplementation()
     }
     
-    open var streamError: NSError? {
+    open var streamError: Error? {
         NSRequiresConcreteImplementation()
     }
 }
@@ -160,8 +160,8 @@
         return Stream.Status(rawValue: UInt(CFReadStreamGetStatus(_stream)))!
     }
     
-    open override var streamError: NSError? {
-        return _CFReadStreamCopyError(_stream)?._nsObject
+    open override var streamError: Error? {
+        return _CFReadStreamCopyError(_stream)
     }
 }
 
@@ -224,8 +224,8 @@
         return CFWriteStreamSetProperty(_stream, key.rawValue._cfObject, property)
     }
     
-    open override var streamError: NSError? {
-        return _CFWriteStreamCopyError(_stream)?._nsObject
+    open override var streamError: Error? {
+        return _CFWriteStreamCopyError(_stream)
     }
 }
 
diff --git a/Foundation/NSString.swift b/Foundation/NSString.swift
index 34badff..c8739cc 100644
--- a/Foundation/NSString.swift
+++ b/Foundation/NSString.swift
@@ -369,7 +369,7 @@
         return compare(string, options: mask, range: compareRange, locale: nil)
     }
     
-    public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange, locale: AnyObject?) -> ComparisonResult {
+    public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange, locale: Any?) -> ComparisonResult {
         var res: CFComparisonResult
         if let loc = locale {
             res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), (loc as! NSLocale)._cfObject)
@@ -1183,7 +1183,7 @@
     }
     
     public convenience init?(data: Data, encoding: UInt) {
-        if data.count == 0 {
+        if data.isEmpty {
             self.init("")
         } else {
         guard let cf = data.withUnsafeBytes({ (bytes: UnsafePointer<UInt8>) -> CFString? in
@@ -1432,9 +1432,12 @@
         let range = CFRangeMake(0, CFStringGetLength(cfstring))
         let opts = CFStringCompareFlags(
             kCFCompareAnchored | kCFCompareNonliteral)
-        
-        return CFStringFindWithOptions(cfstring, prefix._cfObject,
+        if prefix.isEmpty {
+            return true
+        } else {
+            return CFStringFindWithOptions(cfstring, prefix._cfObject,
                                        range, opts, nil)
+        } 
     }
     
     public func hasSuffix(_ suffix: String) -> Bool {
@@ -1442,8 +1445,12 @@
         let range = CFRangeMake(0, CFStringGetLength(cfstring))
         let opts = CFStringCompareFlags(
             kCFCompareAnchored | kCFCompareBackwards | kCFCompareNonliteral)
-        return CFStringFindWithOptions(cfstring, suffix._cfObject,
+        if suffix.isEmpty {
+            return true
+        } else {
+            return CFStringFindWithOptions(cfstring, suffix._cfObject,
                                        range, opts, nil)
+        }    
     }
 }
 #endif
diff --git a/Foundation/NSURLAuthenticationChallenge.swift b/Foundation/NSURLAuthenticationChallenge.swift
index 90ac2f5..3fc30b4 100644
--- a/Foundation/NSURLAuthenticationChallenge.swift
+++ b/Foundation/NSURLAuthenticationChallenge.swift
@@ -71,7 +71,7 @@
      @param error The NSError for the authentication failure, if applicable, else nil
      @result An authentication challenge initialized with the specified parameters
      */
-    public init(protectionSpace space: URLProtectionSpace, proposedCredential credential: URLCredential?, previousFailureCount: Int, failureResponse response: URLResponse?, error: NSError?, sender: URLAuthenticationChallengeSender) {
+    public init(protectionSpace space: URLProtectionSpace, proposedCredential credential: URLCredential?, previousFailureCount: Int, failureResponse response: URLResponse?, error: Error?, sender: URLAuthenticationChallengeSender) {
         NSUnimplemented()
     }
     
@@ -156,7 +156,7 @@
      then this method will return the error. Otherwise it will
      return nil.
      */
-    /*@NSCopying*/ open var error: NSError? {
+    /*@NSCopying*/ open var error: Error? {
         get {
             NSUnimplemented()
         }
diff --git a/Foundation/NSURLProtocol.swift b/Foundation/NSURLProtocol.swift
index 5004d1d..4362d71 100644
--- a/Foundation/NSURLProtocol.swift
+++ b/Foundation/NSURLProtocol.swift
@@ -274,7 +274,7 @@
         @result The property stored with the given key, or nil if no property
         had previously been stored with the given key in the given request.
     */
-    open class func property(forKey key: String, in request: URLRequest) -> AnyObject? { NSUnimplemented() }
+    open class func property(forKey key: String, in request: URLRequest) -> Any? { NSUnimplemented() }
     
     /*! 
         @method setProperty:forKey:inRequest:
@@ -287,7 +287,7 @@
         @param key The string to use for the property storage. 
         @param request The request in which to store the property. 
     */
-    open class func setProperty(_ value: AnyObject, forKey key: String, in request: NSMutableURLRequest) { NSUnimplemented() }
+    open class func setProperty(_ value: Any, forKey key: String, in request: NSMutableURLRequest) { NSUnimplemented() }
     
     /*!
         @method removePropertyForKey:inRequest:
diff --git a/Foundation/NSURLSession/HTTPBodySource.swift b/Foundation/NSURLSession/HTTPBodySource.swift
index 03ebd4c..1089a2e 100644
--- a/Foundation/NSURLSession/HTTPBodySource.swift
+++ b/Foundation/NSURLSession/HTTPBodySource.swift
@@ -81,7 +81,7 @@
             return .done
         } else if remaining <= length {
             let r: DispatchData! = data
-            data = nil
+            data = DispatchData.empty 
             return .data(r)
         } else {
             let (chunk, remainder) = splitData(dispatchData: data, atPosition: length)
@@ -167,7 +167,7 @@
             switch (done, data, errno) {
             case (true, _, errno) where errno != 0:
                 self.availableChunk = .errorDetected(Int(errno))
-            case (true, .some(let d), 0) where d.count == 0:
+            case (true, .some(let d), 0) where d.isEmpty:
                 self.append(data: d, endOfFile: true)
             case (true, .some(let d), 0):
                 self.append(data: d, endOfFile: false)
@@ -220,10 +220,10 @@
             let l = min(length, data.count)
             let (head, tail) = splitData(dispatchData: data, atPosition: l)
             
-            availableChunk = (tail.count == 0) ? .empty : .data(tail)
+            availableChunk = tail.isEmpty ? .empty : .data(tail)
             readNextChunk()
             
-            if head.count == 0 {
+            if head.isEmpty {
                 return .retryLater
             } else {
                 return .data(head)
@@ -231,8 +231,8 @@
         case .done(.some(let data)):
             let l = min(length, data.count)
             let (head, tail) = splitData(dispatchData: data, atPosition: l)
-            availableChunk = (tail.count == 0) ? .done(nil) : .done(tail)
-            if (head.count == 0) {
+            availableChunk = tail.isEmpty ? .done(nil) : .done(tail)
+            if head.isEmpty {
                 return .done
             } else {
                 return .data(head)
diff --git a/Foundation/NSXMLElement.swift b/Foundation/NSXMLElement.swift
index 3c3b853..aa12142 100644
--- a/Foundation/NSXMLElement.swift
+++ b/Foundation/NSXMLElement.swift
@@ -109,7 +109,7 @@
                 result.append(XMLNode._objectNodeForNode(attribute))
                 nextAttribute = _CFXMLNodeGetNextSibling(attribute)
             }
-            return result.count > 0 ? result : nil // This appears to be how Darwin does it
+            return !result.isEmpty ? result : nil // This appears to be how Darwin does it
         }
 
         set {
diff --git a/Foundation/Process.swift b/Foundation/Process.swift
index 0ff17c8..70f2c3e 100644
--- a/Foundation/Process.swift
+++ b/Foundation/Process.swift
@@ -23,10 +23,26 @@
     }
 }
 
-private func WEXITSTATUS(_ status: CInt) -> CInt {
+private func WIFEXITED(_ status: Int32) -> Bool {
+    return _WSTATUS(status) == 0
+}
+
+private func _WSTATUS(_ status: Int32) -> Int32 {
+    return status & 0x7f
+}
+
+private func WIFSIGNALED(_ status: Int32) -> Bool {
+    return (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f)
+}
+
+private func WEXITSTATUS(_ status: Int32) -> Int32 {
     return (status >> 8) & 0xff
 }
 
+private func WTERMSIG(_ status: Int32) -> Int32 {
+    return status & 0x7f
+}
+
 private var managerThreadRunLoop : RunLoop? = nil
 private var managerThreadRunLoopIsRunning = false
 private var managerThreadRunLoopIsRunningCondition = NSCondition()
@@ -280,8 +296,15 @@
                 waitResult = waitpid( process.processIdentifier, &exitCode, 0)
 #endif
             } while ( (waitResult == -1) && (errno == EINTR) )
-            
-            process.terminationStatus = WEXITSTATUS( exitCode )
+
+            if WIFSIGNALED(exitCode) {
+                process.terminationStatus = WTERMSIG(exitCode)
+                process.terminationReason = .uncaughtSignal
+            } else {
+                assert(WIFEXITED(exitCode))
+                process.terminationStatus = WEXITSTATUS(exitCode)
+                process.terminationReason = .exit
+            }
             
             // If a termination handler has been set, invoke it on a background thread
             
@@ -429,7 +452,7 @@
     open private(set) var isRunning: Bool = false
     
     open private(set) var terminationStatus: Int32 = 0
-    open var terminationReason: TerminationReason { NSUnimplemented() }
+    open private(set) var terminationReason: TerminationReason = .exit
     
     /*
     A block to be invoked when the process underlying the Process terminates.  Setting the block to nil is valid, and stops the previous block from being invoked, as long as it hasn't started in any way.  The Process is passed as the argument to the block so the block does not have to capture, and thus retain, it.  The block is copied when set.  Only one termination handler block can be set at any time.  The execution context in which the block is invoked is undefined.  If the Process has already finished, the block is executed immediately/soon (not necessarily on the current thread).  If a terminationHandler is set on an Process, the ProcessDidTerminateNotification notification is not posted for that process.  Also note that -waitUntilExit won't wait until the terminationHandler has been fully executed.  You cannot use this property in a concrete subclass of Process which hasn't been updated to include an implementation of the storage and use of it.  
diff --git a/Foundation/URL.swift b/Foundation/URL.swift
index e9ace98..8e1dc04 100644
--- a/Foundation/URL.swift
+++ b/Foundation/URL.swift
@@ -489,7 +489,7 @@
     ///
     /// If the data representation is not a legal URL string as ASCII bytes, the URL object may not behave as expected. If the URL cannot be formed then this will return nil.
     public init?(dataRepresentation: Data, relativeTo url: URL?, isAbsolute: Bool = false) {
-        guard dataRepresentation.count > 0 else { return nil }
+        guard !dataRepresentation.isEmpty else { return nil }
         
         if isAbsolute {
             _url = URL._converted(from: NSURL(absoluteURLWithDataRepresentation: dataRepresentation, relativeTo: url))
diff --git a/TestFoundation/TestNSCalendar.swift b/TestFoundation/TestNSCalendar.swift
index 191b212..bd60c5a 100644
--- a/TestFoundation/TestNSCalendar.swift
+++ b/TestFoundation/TestNSCalendar.swift
@@ -28,7 +28,8 @@
             ("test_copy",test_copy),
             ("test_addingDates", test_addingDates),
             ("test_datesNotOnWeekend", test_datesNotOnWeekend),
-            ("test_datesOnWeekend", test_datesOnWeekend)
+            ("test_datesOnWeekend", test_datesOnWeekend),
+            ("test_customMirror", test_customMirror)
             // Disabled because this fails on linux https://bugs.swift.org/browse/SR-320
             // ("test_currentCalendarRRstability", test_currentCalendarRRstability),
         ]
@@ -63,11 +64,29 @@
         
         var calendar = Calendar(identifier: .gregorian)
         calendar.timeZone = TimeZone(identifier: "UTC")!
-         let components = calendar.dateComponents([.year, .month, .day], from: date)
+        let components = calendar.dateComponents([.year, .month, .day], from: date)
         
         XCTAssertEqual(components.year, 2015)
         XCTAssertEqual(components.month, 12)
         XCTAssertEqual(components.day, 5)
+
+        // Test for problem reported by Malcolm Barclay via swift-corelibs-dev
+        // https://lists.swift.org/pipermail/swift-corelibs-dev/Week-of-Mon-20161128/001031.html
+        let fromDate = Date()
+        let interval = 200
+        let toDate = Date(timeInterval: TimeInterval(interval), since: fromDate)
+        let fromToComponents = calendar.dateComponents([.second], from: fromDate, to: toDate)
+        XCTAssertEqual(fromToComponents.second, interval);
+
+        // Issue with 32-bit CF calendar vector on Linux
+        // Crashes on macOS 10.12.2/Foundation 1349.25
+        // (Possibly related) rdar://24384757
+        /*
+        let interval2 = Int(INT32_MAX) + 1
+        let toDate2 = Date(timeInterval: TimeInterval(interval2), since: fromDate)
+        let fromToComponents2 = calendar.dateComponents([.second], from: fromDate, to: toDate2)
+        XCTAssertEqual(fromToComponents2.second, interval2);
+        */
     }
 
     func test_gettingDatesOnISO8601Calendar() {
@@ -157,6 +176,17 @@
         
         XCTAssertTrue(calendar.isDateInWeekend(sundayInFebruary))
     }
+    
+    func test_customMirror() {
+        let calendar = Calendar(identifier: .gregorian)
+        let calendarMirror = calendar.customMirror
+        
+        XCTAssertEqual(calendar.identifier, calendarMirror.descendant("identifier") as? Calendar.Identifier)
+        XCTAssertEqual(calendar.locale, calendarMirror.descendant("locale") as? Locale)
+        XCTAssertEqual(calendar.timeZone, calendarMirror.descendant("timeZone") as? TimeZone)
+        XCTAssertEqual(calendar.firstWeekday, calendarMirror.descendant("firstWeekDay") as? Int)
+        XCTAssertEqual(calendar.minimumDaysInFirstWeek, calendarMirror.descendant("minimumDaysInFirstWeek") as? Int)
+    }
 }
 
 class TestNSDateComponents: XCTestCase {
diff --git a/TestFoundation/TestNSError.swift b/TestFoundation/TestNSError.swift
new file mode 100644
index 0000000..516f5d3
--- /dev/null
+++ b/TestFoundation/TestNSError.swift
@@ -0,0 +1,36 @@
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+
+
+#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
+    import Foundation
+    import XCTest
+#else
+    import SwiftFoundation
+    import SwiftXCTest
+#endif
+
+
+class TestNSError : XCTestCase {
+    
+    static var allTests: [(String, (TestNSError) -> () throws -> Void)] {
+        return [
+            ("test_LocalizedError_errorDescription", test_LocalizedError_errorDescription),
+        ]
+    }
+    
+    func test_LocalizedError_errorDescription() {
+        struct Error : LocalizedError {
+            var errorDescription: String? { return "error description" }
+        }
+
+        let error = Error()
+        XCTAssertEqual(error.localizedDescription, "error description")
+    }
+}
diff --git a/TestFoundation/TestNSFileManager.swift b/TestFoundation/TestNSFileManager.swift
index 1bdffd3..248afb3 100644
--- a/TestFoundation/TestNSFileManager.swift
+++ b/TestFoundation/TestNSFileManager.swift
@@ -29,6 +29,7 @@
             ("test_pathEnumerator",test_pathEnumerator),
             ("test_contentsOfDirectoryAtPath", test_contentsOfDirectoryAtPath),
             ("test_subpathsOfDirectoryAtPath", test_subpathsOfDirectoryAtPath),
+            ("test_copyItemAtPathToPath", test_copyItemAtPathToPath)
         ]
     }
     
@@ -410,4 +411,67 @@
             XCTFail("Failed to clean up files")
         }
     }
+    
+    func test_copyItemAtPathToPath() {
+        let fm = FileManager.default
+        let srcPath = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)"
+        let destPath = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)"
+        
+        func cleanup() {
+            ignoreError { try fm.removeItem(atPath: srcPath) }
+            ignoreError { try fm.removeItem(atPath: destPath) }
+        }
+        
+        func directoryExists(atPath path: String) -> Bool {
+            var isDir = false
+            let exists = fm.fileExists(atPath: path, isDirectory: &isDir)
+            return exists && isDir
+        }
+        
+        func createDirectory(atPath path: String) {
+            do {
+                try fm.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
+            } catch let error {
+                XCTFail("Unable to create directory: \(error)")
+            }
+            XCTAssertTrue(directoryExists(atPath: path))
+        }
+        
+        func createFile(atPath path: String) {
+            XCTAssertTrue(fm.createFile(atPath: path, contents: Data(), attributes: nil))
+        }
+        
+        cleanup()
+        createFile(atPath: srcPath)
+        do {
+            try fm.copyItem(atPath: srcPath, toPath: destPath)
+        } catch let error {
+            XCTFail("Failed to copy file: \(error)")
+        }
+
+        cleanup()
+        createDirectory(atPath: srcPath)
+        createDirectory(atPath: "\(srcPath)/tempdir")
+        createFile(atPath: "\(srcPath)/tempdir/tempfile")
+        createFile(atPath: "\(srcPath)/tempdir/tempfile2")
+        do {
+            try fm.copyItem(atPath: srcPath, toPath: destPath)
+        } catch let error {
+            XCTFail("Unable to copy directory: \(error)")
+        }
+        XCTAssertTrue(directoryExists(atPath: destPath))
+        XCTAssertTrue(directoryExists(atPath: "\(destPath)/tempdir"))
+        XCTAssertTrue(fm.fileExists(atPath: "\(destPath)/tempdir/tempfile"))
+        XCTAssertTrue(fm.fileExists(atPath: "\(destPath)/tempdir/tempfile2"))
+        
+        if (false == directoryExists(atPath: destPath)) {
+            return
+        }
+        do {
+            try fm.copyItem(atPath: srcPath, toPath: destPath)
+        } catch {
+            return
+        }
+        XCTFail("Copy overwrites a file/folder that already exists")
+    }
 }
diff --git a/TestFoundation/TestNSGeometry.swift b/TestFoundation/TestNSGeometry.swift
index 53bcde3..edd9d37 100644
--- a/TestFoundation/TestNSGeometry.swift
+++ b/TestFoundation/TestNSGeometry.swift
@@ -29,9 +29,12 @@
             ("test_CGPoint_BasicConstruction", test_CGPoint_BasicConstruction),
             ("test_CGSize_BasicConstruction", test_CGSize_BasicConstruction),
             ("test_CGRect_BasicConstruction", test_CGRect_BasicConstruction),
+            ("test_NSEdgeInsets_BasicConstruction", test_NSEdgeInsets_BasicConstruction),
+            ("test_NSEdgeInsetsEqual", test_NSEdgeInsetsEqual),
             ("test_NSMakePoint", test_NSMakePoint),
             ("test_NSMakeSize", test_NSMakeSize),
             ("test_NSMakeRect", test_NSMakeRect),
+            ("test_NSEdgeInsetsMake", test_NSEdgeInsetsMake),
             ("test_NSUnionRect", test_NSUnionRect),
             ("test_NSIntersectionRect", test_NSIntersectionRect),
             ("test_NSOffsetRect", test_NSOffsetRect),
@@ -136,6 +139,28 @@
         XCTAssertEqual(r2.size.height, s.height)
     }
 
+    func test_NSEdgeInsets_BasicConstruction() {
+        let i1 = NSEdgeInsets()
+        XCTAssertEqual(i1.top, CGFloat(0.0))
+        XCTAssertEqual(i1.left, CGFloat(0.0))
+        XCTAssertEqual(i1.bottom, CGFloat(0.0))
+        XCTAssertEqual(i1.right, CGFloat(0.0))
+
+        let i2 = NSEdgeInsets(top: CGFloat(3.6), left: CGFloat(4.5), bottom: CGFloat(5.0), right: CGFloat(-1.0))
+        XCTAssertEqual(i2.top, CGFloat(3.6))
+        XCTAssertEqual(i2.left, CGFloat(4.5))
+        XCTAssertEqual(i2.bottom, CGFloat(5.0))
+        XCTAssertEqual(i2.right, CGFloat(-1.0))
+    }
+
+    func test_NSEdgeInsetsEqual() {
+        let variant1 = NSEdgeInsets(top: CGFloat(3.6), left: CGFloat(4.5), bottom: CGFloat(5.0), right: CGFloat(-1.0))
+        let variant1Copy = NSEdgeInsets(top: CGFloat(3.6), left: CGFloat(4.5), bottom: CGFloat(5.0), right: CGFloat(-1.0))
+        let variant2 = NSEdgeInsets(top: CGFloat(3.1), left: CGFloat(4.5), bottom: CGFloat(5.0), right: CGFloat(-1.0))
+        XCTAssertTrue(NSEdgeInsetsEqual(variant1, variant1Copy))
+        XCTAssertFalse(NSEdgeInsetsEqual(variant1, variant2))
+    }
+
     func test_NSMakePoint() {
         let p2 = NSMakePoint(CGFloat(3.6), CGFloat(4.5))
         XCTAssertEqual(p2.x, CGFloat(3.6))
@@ -156,6 +181,14 @@
         XCTAssertEqual(r2.size.height, CGFloat(5.0))
     }
 
+    func test_NSEdgeInsetsMake() {
+        let i2 = NSEdgeInsetsMake(CGFloat(2.2), CGFloat(3.0), CGFloat(5.0), CGFloat(5.0))
+        XCTAssertEqual(i2.top, CGFloat(2.2))
+        XCTAssertEqual(i2.left, CGFloat(3.0))
+        XCTAssertEqual(i2.bottom, CGFloat(5.0))
+        XCTAssertEqual(i2.right, CGFloat(5.0))
+    }
+
     func test_NSUnionRect() {
         let r1 = NSMakeRect(CGFloat(1.2), CGFloat(3.1), CGFloat(10.0), CGFloat(10.0))
         let r2 = NSMakeRect(CGFloat(10.2), CGFloat(2.5), CGFloat(5.0), CGFloat(5.0))
@@ -275,87 +308,87 @@
         let referenceNegativeRect = NSMakeRect(CGFloat(-0.6), CGFloat(-5.4), CGFloat(-105.7), CGFloat(-24.3))
         let referenceNegativeOriginRect = NSMakeRect(CGFloat(-0.6), CGFloat(-5.4), CGFloat(105.7), CGFloat(24.3))
 
-        var options: NSAlignmentOptions = [.AlignMinXInward, .AlignMinYInward, .AlignHeightInward, .AlignWidthInward]
+        var options: AlignmentOptions = [.alignMinXInward, .alignMinYInward, .alignHeightInward, .alignWidthInward]
         var expectedResult = NSMakeRect(CGFloat(1.0), CGFloat(6.0), CGFloat(105.0), CGFloat(24.0))
         var result = NSIntegralRectWithOptions(referenceRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMinXOutward, .AlignMinYOutward, .AlignHeightOutward, .AlignWidthOutward]
+        options = [.alignMinXOutward, .alignMinYOutward, .alignHeightOutward, .alignWidthOutward]
         expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(5.0), CGFloat(106.0), CGFloat(25.0))
         result = NSIntegralRectWithOptions(referenceRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMinXInward, .AlignMinYInward, .AlignHeightInward, .AlignWidthInward]
+        options = [.alignMinXInward, .alignMinYInward, .alignHeightInward, .alignWidthInward]
         expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(-5.0), CGFloat(0.0), CGFloat(0.0))
         result = NSIntegralRectWithOptions(referenceNegativeRect, options)
         XCTAssertEqual(result, expectedResult)
         
-        options = [.AlignMinXInward, .AlignMinYInward, .AlignHeightInward, .AlignWidthInward]
+        options = [.alignMinXInward, .alignMinYInward, .alignHeightInward, .alignWidthInward]
         expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(-5.0), CGFloat(105.0), CGFloat(24.0))
         result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMinXOutward, .AlignMinYOutward, .AlignHeightOutward, .AlignWidthOutward]
+        options = [.alignMinXOutward, .alignMinYOutward, .alignHeightOutward, .alignWidthOutward]
         expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-6.0), CGFloat(106.0), CGFloat(25.0))
         result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMaxXOutward, .AlignMaxYOutward, .AlignHeightOutward, .AlignWidthOutward]
+        options = [.alignMaxXOutward, .alignMaxYOutward, .alignHeightOutward, .alignWidthOutward]
         expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(-6.0), CGFloat(106.0), CGFloat(25.0))
         result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMinXOutward, .AlignMaxXOutward, .AlignMinYOutward, .AlignMaxYOutward]
+        options = [.alignMinXOutward, .alignMaxXOutward, .alignMinYOutward, .alignMaxYOutward]
         expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-6.0), CGFloat(107.0), CGFloat(25.0))
         result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMaxXOutward, .AlignMaxYOutward, .AlignHeightOutward, .AlignWidthOutward]
+        options = [.alignMaxXOutward, .alignMaxYOutward, .alignHeightOutward, .alignWidthOutward]
         expectedResult = NSMakeRect(CGFloat(1.0), CGFloat(5.0), CGFloat(106.0), CGFloat(25.0))
         result = NSIntegralRectWithOptions(referenceRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMaxXInward, .AlignMaxYInward, .AlignHeightOutward, .AlignWidthOutward]
+        options = [.alignMaxXInward, .alignMaxYInward, .alignHeightOutward, .alignWidthOutward]
         expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-7.0), CGFloat(106.0), CGFloat(25.0))
         result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMaxXInward, .AlignMaxYInward, .AlignHeightOutward, .AlignWidthOutward]
+        options = [.alignMaxXInward, .alignMaxYInward, .alignHeightOutward, .alignWidthOutward]
         expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(4.0), CGFloat(106.0), CGFloat(25.0))
         result = NSIntegralRectWithOptions(referenceRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMinXNearest, .AlignMinYNearest, .AlignHeightNearest, .AlignWidthNearest]
+        options = [.alignMinXNearest, .alignMinYNearest, .alignHeightNearest, .alignWidthNearest]
         expectedResult = NSMakeRect(CGFloat(1.0), CGFloat(5.0), CGFloat(106.0), CGFloat(24.0))
         result = NSIntegralRectWithOptions(referenceRect, options)
         XCTAssertEqual(result, expectedResult)
         
-        options = [.AlignMinXNearest, .AlignMinYNearest, .AlignHeightNearest, .AlignWidthNearest]
+        options = [.alignMinXNearest, .alignMinYNearest, .alignHeightNearest, .alignWidthNearest]
         expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-5.0), CGFloat(106.0), CGFloat(24.0))
         result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMaxXNearest, .AlignMaxYNearest, .AlignHeightNearest, .AlignWidthNearest]
+        options = [.alignMaxXNearest, .alignMaxYNearest, .alignHeightNearest, .alignWidthNearest]
         expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(6.0), CGFloat(106.0), CGFloat(24.0))
         result = NSIntegralRectWithOptions(referenceRect, options)
         XCTAssertEqual(result, expectedResult)
         
-        options = [.AlignMaxXNearest, .AlignMaxYNearest, .AlignHeightNearest, .AlignWidthNearest]
+        options = [.alignMaxXNearest, .alignMaxYNearest, .alignHeightNearest, .alignWidthNearest]
         expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-5.0), CGFloat(106.0), CGFloat(24.0))
         result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMinXInward, .AlignMaxXInward, .AlignMinYInward, .AlignMaxYInward]
+        options = [.alignMinXInward, .alignMaxXInward, .alignMinYInward, .alignMaxYInward]
         expectedResult = NSMakeRect(CGFloat(1.0), CGFloat(6.0), CGFloat(105.0), CGFloat(23.0))
         result = NSIntegralRectWithOptions(referenceRect, options)
         XCTAssertEqual(result, expectedResult)
         
-        options = [.AlignMinXInward, .AlignMaxXInward, .AlignMinYInward, .AlignMaxYInward]
+        options = [.alignMinXInward, .alignMaxXInward, .alignMinYInward, .alignMaxYInward]
         expectedResult = NSMakeRect(CGFloat(0.0), CGFloat(-5.0), CGFloat(105.0), CGFloat(23.0))
         result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
         XCTAssertEqual(result, expectedResult)
 
-        options = [.AlignMinXNearest, .AlignMaxXInward, .AlignMinYInward, .AlignMaxYNearest]
+        options = [.alignMinXNearest, .alignMaxXInward, .alignMinYInward, .alignMaxYNearest]
         expectedResult = NSMakeRect(CGFloat(-1.0), CGFloat(-5.0), CGFloat(106.0), CGFloat(24.0))
         result = NSIntegralRectWithOptions(referenceNegativeOriginRect, options)
         XCTAssertEqual(result, expectedResult)
diff --git a/TestFoundation/TestNSHTTPCookie.swift b/TestFoundation/TestNSHTTPCookie.swift
index 6fd0e27..a8f68ba 100644
--- a/TestFoundation/TestNSHTTPCookie.swift
+++ b/TestFoundation/TestNSHTTPCookie.swift
@@ -125,7 +125,7 @@
                       "Set-Cookie": "fr=anjd&232; Max-Age=7776000; path=/; domain=.example.com; secure; httponly",
                       "header2":"value2",
                       "header3":"value3"]
-        let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, forURL: URL(string: "http://example.com")!)
+        let cookies = HTTPCookie.cookies(withResponseHeaderFields: header, for: URL(string: "http://example.com")!)
         XCTAssertEqual(cookies.count, 1)
         XCTAssertEqual(cookies[0].name, "fr")
         XCTAssertEqual(cookies[0].value, "anjd&232")
@@ -133,7 +133,7 @@
 
     func test_cookiesWithResponseHeader0cookies() {
         let header = ["header1":"value1", "header2":"value2", "header3":"value3"]
-        let cookies =  HTTPCookie.cookies(withResponseHeaderFields: header, forURL: URL(string: "http://example.com")!)
+        let cookies =  HTTPCookie.cookies(withResponseHeaderFields: header, for: URL(string: "http://example.com")!)
         XCTAssertEqual(cookies.count, 0)
     }
 
@@ -142,7 +142,7 @@
                       "Set-Cookie": "fr=a&2@#; Max-Age=1186000; path=/; domain=.example.com; secure, xd=plm!@#;path=/;domain=.example2.com", 
                       "header2":"value2",
                       "header3":"value3"]
-        let cookies =  HTTPCookie.cookies(withResponseHeaderFields: header, forURL: URL(string: "http://example.com")!)
+        let cookies =  HTTPCookie.cookies(withResponseHeaderFields: header, for: URL(string: "http://example.com")!)
         XCTAssertEqual(cookies.count, 2)
         XCTAssertTrue(cookies[0].isSecure)
         XCTAssertFalse(cookies[1].isSecure)
@@ -153,7 +153,7 @@
                        "Set-Cookie": "fr=anjd&232; expires=Wed, 21 Sep 2016 05:33:00 GMT; Max-Age=7776000; path=/; secure; httponly",
                        "header2":"value2",
                        "header3":"value3"]
-        let cookies =  HTTPCookie.cookies(withResponseHeaderFields: header, forURL: URL(string: "http://example.com")!)
+        let cookies =  HTTPCookie.cookies(withResponseHeaderFields: header, for: URL(string: "http://example.com")!)
         XCTAssertEqual(cookies[0].domain, "http://example.com")
         XCTAssertNotNil(cookies[0].expiresDate)
 
@@ -173,7 +173,7 @@
                       "Set-Cookie": "fr=tx; expires=Wed, 21-Sep-2016 05:33:00 GMT; Max-Age=7776000; secure; httponly", 
                       "header2":"value2",
                       "header3":"value3"]
-        let cookies =  HTTPCookie.cookies(withResponseHeaderFields: header, forURL: URL(string: "http://example.com")!)
+        let cookies =  HTTPCookie.cookies(withResponseHeaderFields: header, for: URL(string: "http://example.com")!)
         XCTAssertEqual(cookies[0].domain, "http://example.com")
         XCTAssertEqual(cookies[0].path, "/")
     }
diff --git a/TestFoundation/TestNSKeyedArchiver.swift b/TestFoundation/TestNSKeyedArchiver.swift
index 6e6b529..32fd2b6 100644
--- a/TestFoundation/TestNSKeyedArchiver.swift
+++ b/TestFoundation/TestNSKeyedArchiver.swift
@@ -111,6 +111,7 @@
 
     private func test_archive(_ encode: (NSKeyedArchiver) -> Bool,
                               decode: (NSKeyedUnarchiver) -> Bool) {
+        // Archiving using custom NSMutableData instance
         let data = NSMutableData()
         let archiver = NSKeyedArchiver(forWritingWith: data)
         
@@ -119,6 +120,15 @@
         
         let unarchiver = NSKeyedUnarchiver(forReadingWithData: Data._unconditionallyBridgeFromObjectiveC(data))
         XCTAssertTrue(decode(unarchiver))
+        
+        // Archiving using the default initializer
+        let archiver1 = NSKeyedArchiver()
+        
+        XCTAssertTrue(encode(archiver1))
+        let archivedData = archiver1.encodedData
+        
+        let unarchiver1 = NSKeyedUnarchiver(forReadingWithData: archivedData)
+        XCTAssertTrue(decode(unarchiver1))
     }
     
     private func test_archive(_ object: Any, classes: [AnyClass], allowsSecureCoding: Bool = true, outputFormat: PropertyListSerialization.PropertyListFormat) {
diff --git a/TestFoundation/TestNSString.swift b/TestFoundation/TestNSString.swift
index 0671f99..34bd07b 100644
--- a/TestFoundation/TestNSString.swift
+++ b/TestFoundation/TestNSString.swift
@@ -90,6 +90,7 @@
             ("test_deletingPathExtension", test_deletingPathExtension),
             ("test_ExternalRepresentation", test_ExternalRepresentation),
             ("test_mutableStringConstructor", test_mutableStringConstructor),
+            ("test_emptyStringPrefixAndSuffix",test_emptyStringPrefixAndSuffix),
             ("test_PrefixSuffix", test_PrefixSuffix),
             ("test_utf16StringRangeCount", test_StringUTF16ViewIndexStrideableRange),
             ("test_reflection", { _ in test_reflection }),
@@ -1056,6 +1057,12 @@
         XCTAssertEqual(outContentsEndIndex, twoLines.index(twoLines.startIndex, offsetBy: 11))
         XCTAssertEqual(outEndIndex, twoLines.index(twoLines.startIndex, offsetBy: 12))
     }
+    
+    func test_emptyStringPrefixAndSuffix() {
+        let testString = "hello"
+        XCTAssertTrue(testString.hasPrefix(""))
+        XCTAssertTrue(testString.hasSuffix(""))
+    }
 }
 
 struct ComparisonTest {
@@ -1086,7 +1093,8 @@
     // ASCII cases
     ComparisonTest("t", "tt"),
     ComparisonTest("t", "Tt"),
-    ComparisonTest("\u{0}", ""),
+    ComparisonTest("\u{0}", "",
+        reason: "https://bugs.swift.org/browse/SR-332"),
     ComparisonTest("\u{0}", "\u{0}",
         reason: "https://bugs.swift.org/browse/SR-332"),
     ComparisonTest("\r\n", "t"),
@@ -1183,16 +1191,20 @@
 }
 
 func checkHasPrefixHasSuffix(_ lhs: String, _ rhs: String, _ stack: [UInt]) -> Int {
-    if lhs == "" {
+    if (lhs == "" && rhs == "") {
+        var failures = 0
+        failures += lhs.hasPrefix(rhs) ? 0: 1
+        failures += lhs.hasSuffix(rhs) ? 0: 1
+        return failures
+    } else if lhs == "" {
         var failures = 0
         failures += lhs.hasPrefix(rhs) ? 1 : 0
         failures += lhs.hasSuffix(rhs) ? 1 : 0
         return failures
-    }
-    if rhs == "" {
+    } else if rhs == "" {
         var failures = 0
-        failures += lhs.hasPrefix(rhs) ? 1 : 0
-        failures += lhs.hasSuffix(rhs) ? 1 : 0
+        failures += lhs.hasPrefix(rhs) ? 0 : 1 
+        failures += lhs.hasSuffix(rhs) ? 0 : 1 
         return failures
     }
 
@@ -1228,7 +1240,6 @@
 
 extension TestNSString {
     func test_PrefixSuffix() {
-#if !_runtime(_ObjC)
         for test in comparisonTests {
             var failures = 0
             failures += checkHasPrefixHasSuffix(test.lhs, test.rhs, [test.loc, #line])
@@ -1249,7 +1260,6 @@
             }
             XCTAssert(test.xfail == fail, "Unexpected \(test.xfail ?"success":"failure"): \(test.loc)")
         }
-#endif
     }
 }
 
diff --git a/TestFoundation/TestProcess.swift b/TestFoundation/TestProcess.swift
index 9b6633a..cbac7a9 100644
--- a/TestFoundation/TestProcess.swift
+++ b/TestFoundation/TestProcess.swift
@@ -24,6 +24,7 @@
                    ("test_exit100" , test_exit100),
                    ("test_sleep2", test_sleep2),
                    ("test_sleep2_exit1", test_sleep2_exit1),
+                   ("test_terminationReason_uncaughtSignal", test_terminationReason_uncaughtSignal),
                    ("test_pipe_stdin", test_pipe_stdin),
                    ("test_pipe_stdout", test_pipe_stdout),
                    ("test_pipe_stderr", test_pipe_stderr),
@@ -47,6 +48,7 @@
         process.launch()
         process.waitUntilExit()
         XCTAssertEqual(process.terminationStatus, 0)
+        XCTAssertEqual(process.terminationReason, .exit)
     }
     
     func test_exit1() {
@@ -59,6 +61,7 @@
         process.launch()
         process.waitUntilExit()
         XCTAssertEqual(process.terminationStatus, 1)
+        XCTAssertEqual(process.terminationReason, .exit)
     }
     
     func test_exit100() {
@@ -71,6 +74,7 @@
         process.launch()
         process.waitUntilExit()
         XCTAssertEqual(process.terminationStatus, 100)
+        XCTAssertEqual(process.terminationReason, .exit)
     }
     
     func test_sleep2() {
@@ -83,6 +87,7 @@
         process.launch()
         process.waitUntilExit()
         XCTAssertEqual(process.terminationStatus, 0)
+        XCTAssertEqual(process.terminationReason, .exit)
     }
     
     func test_sleep2_exit1() {
@@ -95,8 +100,20 @@
         process.launch()
         process.waitUntilExit()
         XCTAssertEqual(process.terminationStatus, 1)
+        XCTAssertEqual(process.terminationReason, .exit)
     }
 
+    func test_terminationReason_uncaughtSignal() {
+        let process = Process()
+
+        process.launchPath = "/bin/bash"
+        process.arguments = ["-c", "kill -TERM $$"]
+
+        process.launch()
+        process.waitUntilExit()
+        XCTAssertEqual(process.terminationStatus, 15)
+        XCTAssertEqual(process.terminationReason, .uncaughtSignal)
+    }
 
     func test_pipe_stdin() {
         let process = Process()
diff --git a/TestFoundation/main.swift b/TestFoundation/main.swift
index ede808f..b407103 100644
--- a/TestFoundation/main.swift
+++ b/TestFoundation/main.swift
@@ -34,6 +34,7 @@
     testCase(TestNSDateFormatter.allTests),
     testCase(TestNSDecimal.allTests),
     testCase(TestNSDictionary.allTests),
+    testCase(TestNSError.allTests),
     testCase(TestNSFileManager.allTests),
     testCase(TestNSGeometry.allTests),
     testCase(TestNSHTTPCookie.allTests),
diff --git a/build.py b/build.py
index ac4e8f7..450168e 100644
--- a/build.py
+++ b/build.py
@@ -337,7 +337,7 @@
 	'Foundation/NSFileManager.swift',
 	'Foundation/NSFormatter.swift',
 	'Foundation/NSGeometry.swift',
-	'Foundation/NSHost.swift',
+	'Foundation/Host.swift',
 	'Foundation/NSHTTPCookie.swift',
 	'Foundation/NSHTTPCookieStorage.swift',
 	'Foundation/NSIndexPath.swift',