Merge pull request #700 from KingOfBrian/bugfix/SR-2301

diff --git a/CoreFoundation/Locale.subproj/CFLocale.c b/CoreFoundation/Locale.subproj/CFLocale.c
index b502faf..69dda52 100644
--- a/CoreFoundation/Locale.subproj/CFLocale.c
+++ b/CoreFoundation/Locale.subproj/CFLocale.c
@@ -280,7 +280,12 @@
 
 
 #if DEPLOYMENT_TARGET_MACOSX
+// Specify a default locale on Mac for Swift
+#if DEPLOYMENT_RUNTIME_SWIFT
+#define FALLBACK_LOCALE_NAME CFSTR("en_US")
+#else
 #define FALLBACK_LOCALE_NAME CFSTR("")
+#endif /* DEPLOYMENT_RUNTIME_SWIFT */
 #elif DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI
 #define FALLBACK_LOCALE_NAME CFSTR("en_US")
 #elif DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
diff --git a/Docs/Status.md b/Docs/Status.md
index de77b21..e3b8d0b 100644
--- a/Docs/Status.md
+++ b/Docs/Status.md
@@ -47,16 +47,16 @@
     |------------------------------|-----------------|---------------|--------------------------------------------------------------------------------------------------------------------|
     | `URLAuthenticationChallenge` | Unimplemented   | None          |                                                                                                                    |
     | `URLCache`                   | Unimplemented   | None          |                                                                                                                    |
-    | `URLCredential`              | Mostly Complete | Incomplete    | `NSCoding` and `NSCopying` remain unimplemented                                                                    |
+    | `URLCredential`              | Mostly Complete | Incomplete    | `NSCopying` remains unimplemented                                                                                  |
     | `URLCredentialStorage`       | Unimplemented   | None          |                                                                                                                    |
     | `NSURLError*`                | Complete        | N/A           |                                                                                                                    |
     | `URLProtectionSpace`         | Unimplemented   | None          |                                                                                                                    |
     | `URLProtocol`                | Unimplemented   | None          |                                                                                                                    |
     | `URLProtocolClient`          | Unimplemented   | None          |                                                                                                                    |
-    | `NSURLRequest`               | Mostly Complete | Incomplete    | `NSCoding` remains unimplemented                                                                                   |
-    | `NSMutableURLRequest`        | Mostly Complete | Incomplete    | `NSCoding` remains unimplemented                                                                                   |
-    | `URLResponse`                | Mostly Complete | Incomplete    | `NSCoding` remains unimplemented                                                                                   |
-    | `NSHTTPURLResponse`          | Mostly Complete | Substantial   | `NSCoding` remains unimplemented                                                                                   |
+    | `NSURLRequest`               | Mostly Complete | Incomplete    |                                                                                                                    |
+    | `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 |
     | `NSURLQueryItem`             | Mostly Complete | N/A           | `NSCoding` remains unimplemented                                                                                   |
     | `URLResourceKey`             | Complete        | N/A           |                                                                                                                    |
diff --git a/Foundation.xcodeproj/project.pbxproj b/Foundation.xcodeproj/project.pbxproj
old mode 100755
new mode 100644
index 45e43e4..2af4035
--- a/Foundation.xcodeproj/project.pbxproj
+++ b/Foundation.xcodeproj/project.pbxproj
@@ -308,6 +308,7 @@
 		7900433B1CACD33E00ECCBF1 /* TestNSCompoundPredicate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 790043391CACD33E00ECCBF1 /* TestNSCompoundPredicate.swift */; };
 		7900433C1CACD33E00ECCBF1 /* TestNSPredicate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7900433A1CACD33E00ECCBF1 /* TestNSPredicate.swift */; };
 		AE35A1861CBAC85E0042DB84 /* SwiftFoundation.h in Headers */ = {isa = PBXBuildFile; fileRef = AE35A1851CBAC85E0042DB84 /* SwiftFoundation.h */; settings = {ATTRIBUTES = (Public, ); }; };
+		BF8E65311DC3B3CB005AB5C3 /* TestNotification.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF8E65301DC3B3CB005AB5C3 /* TestNotification.swift */; };
 		CC5249C01D341D23007CB54D /* TestUnitConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC5249BF1D341D23007CB54D /* TestUnitConverter.swift */; };
 		CE19A88C1C23AA2300B4CB6A /* NSStringTestData.txt in Resources */ = {isa = PBXBuildFile; fileRef = CE19A88B1C23AA2300B4CB6A /* NSStringTestData.txt */; };
 		D31302011C30CEA900295652 /* NSConcreteValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = D31302001C30CEA900295652 /* NSConcreteValue.swift */; };
@@ -744,6 +745,7 @@
 		88D28DE61C13AE9000494606 /* TestNSGeometry.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSGeometry.swift; sourceTree = "<group>"; };
 		A5A34B551C18C85D00FD972B /* TestNSByteCountFormatter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSByteCountFormatter.swift; sourceTree = "<group>"; };
 		AE35A1851CBAC85E0042DB84 /* SwiftFoundation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SwiftFoundation.h; sourceTree = "<group>"; };
+		BF8E65301DC3B3CB005AB5C3 /* TestNotification.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNotification.swift; sourceTree = "<group>"; };
 		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>"; };
@@ -1378,6 +1380,7 @@
 				0383A1741D2E558A0052E5D1 /* TestNSStream.swift */,
 				5B1FD9E21D6D17B80080E83C /* TestNSURLSession.swift */,
 				EA54A6FA1DB16D53009E0809 /* TestObjCRuntime.swift */,
+				BF8E65301DC3B3CB005AB5C3 /* TestNotification.swift */,
 			);
 			name = Tests;
 			sourceTree = "<group>";
@@ -2215,6 +2218,7 @@
 				5B13B34D1C582D4C00651CE2 /* TestNSUUID.swift in Sources */,
 				5B13B3281C582D4C00651CE2 /* TestNSBundle.swift in Sources */,
 				5B13B32A1C582D4C00651CE2 /* TestNSCharacterSet.swift in Sources */,
+				BF8E65311DC3B3CB005AB5C3 /* TestNotification.swift in Sources */,
 				EA01AAEC1DA839C4008F4E07 /* TestProgress.swift in Sources */,
 				5B13B3411C582D4C00651CE2 /* TestNSRegularExpression.swift in Sources */,
 				5B13B3491C582D4C00651CE2 /* TestNSTimeZone.swift in Sources */,
diff --git a/Foundation/CGFloat.swift b/Foundation/CGFloat.swift
index bba73b4..3462d8d 100644
--- a/Foundation/CGFloat.swift
+++ b/Foundation/CGFloat.swift
@@ -145,15 +145,17 @@
     public var native: NativeType
 }
 
-@_transparent extension CGFloat : BinaryFloatingPoint {
+extension CGFloat : BinaryFloatingPoint {
     
     public typealias RawSignificand = UInt
     public typealias Exponent = Int
-    
+
+    @_transparent
     public static var exponentBitCount: Int {
         return NativeType.exponentBitCount
     }
     
+    @_transparent
     public static var significandBitCount: Int {
         return NativeType.significandBitCount
     }
@@ -161,10 +163,12 @@
     //  Conversions to/from integer encoding.  These are not part of the
     //  BinaryFloatingPoint prototype because there's no guarantee that an
     //  integer type of the same size actually exists (e.g. Float80).
+    @_transparent
     public var bitPattern: UInt {
         return UInt(native.bitPattern)
     }
-    
+
+    @_transparent
     public init(bitPattern: UInt) {
 #if arch(i386) || arch(arm)
         native = NativeType(bitPattern: UInt32(bitPattern))
@@ -172,19 +176,23 @@
         native = NativeType(bitPattern: UInt64(bitPattern))
 #endif
     }
-    
+
+    @_transparent
     public var sign: FloatingPointSign {
         return native.sign
     }
-    
+
+    @_transparent
     public var exponentBitPattern: UInt {
         return native.exponentBitPattern
     }
-    
+
+    @_transparent
     public var significandBitPattern: UInt {
         return UInt(native.significandBitPattern)
     }
-    
+
+    @_transparent
     public init(sign: FloatingPointSign,
                 exponentBitPattern: UInt,
                 significandBitPattern: UInt) {
@@ -192,177 +200,217 @@
                             exponentBitPattern: exponentBitPattern,
                             significandBitPattern: NativeType.RawSignificand(significandBitPattern))
     }
-    
+
+    @_transparent
     public init(nan payload: RawSignificand, signaling: Bool) {
         native = NativeType(nan: NativeType.RawSignificand(payload),
                             signaling: signaling)
     }
-    
+
+    @_transparent
     public static var infinity: CGFloat {
         return CGFloat(NativeType.infinity)
     }
-    
+
+    @_transparent
     public static var nan: CGFloat {
         return CGFloat(NativeType.nan)
     }
-    
+
+    @_transparent
     public static var signalingNaN: CGFloat {
         return CGFloat(NativeType.signalingNaN)
     }
-    
+
     @available(*, unavailable, renamed: "nan")
     public static var quietNaN: CGFloat {
         fatalError("unavailable")
     }
-    
+
+    @_transparent
     public static var greatestFiniteMagnitude: CGFloat {
         return CGFloat(NativeType.greatestFiniteMagnitude)
     }
-    
+
+    @_transparent
     public static var pi: CGFloat {
         return CGFloat(NativeType.pi)
     }
-    
+
+    @_transparent
     public var ulp: CGFloat {
         return CGFloat(native.ulp)
     }
-    
+
+    @_transparent
     public static var leastNormalMagnitude: CGFloat {
         return CGFloat(NativeType.leastNormalMagnitude)
     }
-    
+
+    @_transparent
     public static var leastNonzeroMagnitude: CGFloat {
         return CGFloat(NativeType.leastNonzeroMagnitude)
     }
-    
+
+    @_transparent
     public var exponent: Int {
         return native.exponent
     }
-    
+
+    @_transparent
     public var significand: CGFloat {
         return CGFloat(native.significand)
     }
-    
+
+    @_transparent
     public init(sign: FloatingPointSign, exponent: Int, significand: CGFloat) {
         native = NativeType(sign: sign,
                             exponent: exponent, significand: significand.native)
     }
-    
+
+    @_transparent
     public mutating func round(_ rule: FloatingPointRoundingRule) {
         native.round(rule)
     }
-    
+
+    @_transparent
     public var nextUp: CGFloat {
         return CGFloat(native.nextUp)
     }
-    
+
+    @_transparent
     public var magnitude: CGFloat {
         return CGFloat(Swift.abs(native))
     }
-    
+
+    @_transparent
     public mutating func negate() {
         native.negate()
     }
-    
+
+    @_transparent
     public mutating func add(_ other: CGFloat) {
         native.add(other.native)
     }
-    
+
+    @_transparent
     public mutating func subtract(_ other: CGFloat) {
         native.subtract(other.native)
     }
-    
+
+    @_transparent
     public mutating func multiply(by other: CGFloat) {
         native.multiply(by: other.native)
     }
-    
+
+    @_transparent
     public mutating func divide(by other: CGFloat) {
         native.divide(by: other.native)
     }
-    
+
+    @_transparent
     public mutating func formTruncatingRemainder(dividingBy other: CGFloat) {
         native.formTruncatingRemainder(dividingBy: other.native)
     }
-    
+
+    @_transparent
     public mutating func formRemainder(dividingBy other: CGFloat) {
         native.formRemainder(dividingBy: other.native)
     }
-    
+
+    @_transparent
     public mutating func formSquareRoot( ) {
         native.formSquareRoot( )
     }
-    
+
+    @_transparent
     public mutating func addProduct(_ lhs: CGFloat, _ rhs: CGFloat) {
         native.addProduct(lhs.native, rhs.native)
     }
-    
+
+    @_transparent
     public func isEqual(to other: CGFloat) -> Bool {
         return self.native.isEqual(to: other.native)
     }
-    
+
+    @_transparent
     public func isLess(than other: CGFloat) -> Bool {
         return self.native.isLess(than: other.native)
     }
-    
+
+    @_transparent
     public func isLessThanOrEqualTo(_ other: CGFloat) -> Bool {
         return self.native.isLessThanOrEqualTo(other.native)
     }
-    
+
+    @_transparent
     public var isNormal:  Bool {
         return native.isNormal
     }
-    
+
+    @_transparent
     public var isFinite:  Bool {
         return native.isFinite
     }
-    
+
+    @_transparent
     public var isZero:  Bool {
         return native.isZero
     }
-    
+
+    @_transparent
     public var isSubnormal:  Bool {
         return native.isSubnormal
     }
-    
+
+    @_transparent
     public var isInfinite:  Bool {
         return native.isInfinite
     }
-    
+
+    @_transparent
     public var isNaN:  Bool {
         return native.isNaN
     }
-    
+
+    @_transparent
     public var isSignalingNaN: Bool {
         return native.isSignalingNaN
     }
-    
+
     @available(*, unavailable, renamed: "isSignalingNaN")
     public var isSignaling: Bool {
         fatalError("unavailable")
     }
-    
+
+    @_transparent
     public var isCanonical: Bool {
         return true
     }
-    
+
+    @_transparent
     public var floatingPointClass: FloatingPointClassification {
         return native.floatingPointClass
     }
-    
+
+    @_transparent
     public var binade: CGFloat {
         return CGFloat(native.binade)
     }
-    
+
+    @_transparent
     public var significandWidth: Int {
         return native.significandWidth
     }
-    
+
     /// Create an instance initialized to `value`.
+    @_transparent
     public init(floatLiteral value: NativeType) {
         native = value
     }
-    
+
     /// Create an instance initialized to `value`.
+    @_transparent
     public init(integerLiteral value: Int) {
         native = NativeType(value)
     }
@@ -402,14 +450,14 @@
     }
 }
 
-@_transparent extension CGFloat : CustomStringConvertible {
+extension CGFloat : CustomStringConvertible {
     /// A textual representation of `self`.
     public var description: String {
         return native.description
     }
 }
 
-@_transparent extension CGFloat : Hashable {
+extension CGFloat : Hashable {
     /// The hash value.
     ///
     /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
@@ -417,78 +465,91 @@
     /// - Note: the hash value is not guaranteed to be stable across
     ///   different invocations of the same program.  Do not persist the
     ///   hash value across program runs.
+    @_transparent
     public var hashValue: Int {
         return native.hashValue
     }
 }
 
-@_transparent extension UInt8 {
+extension UInt8 {
+    @_transparent
     public init(_ value: CGFloat) {
         self = UInt8(value.native)
     }
 }
 
-@_transparent extension Int8 {
+extension Int8 {
+    @_transparent
     public init(_ value: CGFloat) {
         self = Int8(value.native)
     }
 }
 
-@_transparent extension UInt16 {
+extension UInt16 {
+    @_transparent
     public init(_ value: CGFloat) {
         self = UInt16(value.native)
     }
 }
 
-@_transparent extension Int16 {
+extension Int16 {
+    @_transparent
     public init(_ value: CGFloat) {
         self = Int16(value.native)
     }
 }
 
-@_transparent extension UInt32 {
+extension UInt32 {
+    @_transparent
     public init(_ value: CGFloat) {
         self = UInt32(value.native)
     }
 }
 
-@_transparent extension Int32 {
+extension Int32 {
+    @_transparent
     public init(_ value: CGFloat) {
         self = Int32(value.native)
     }
 }
 
-@_transparent extension UInt64 {
+extension UInt64 {
+    @_transparent
     public init(_ value: CGFloat) {
         self = UInt64(value.native)
     }
 }
 
-@_transparent extension Int64 {
+extension Int64 {
+    @_transparent
     public init(_ value: CGFloat) {
         self = Int64(value.native)
     }
 }
 
-@_transparent extension UInt {
+extension UInt {
+    @_transparent
     public init(_ value: CGFloat) {
         self = UInt(value.native)
     }
 }
 
-@_transparent extension Int {
+extension Int {
+    @_transparent
     public init(_ value: CGFloat) {
         self = Int(value.native)
     }
 }
 
-@_transparent extension Double {
+extension Double {
+    @_transparent
     public init(_ value: CGFloat) {
         self = Double(value.native)
     }
 }
 
-@_transparent extension Float {
+extension Float {
+    @_transparent
     public init(_ value: CGFloat) {
         self = Float(value.native)
     }
@@ -547,7 +608,7 @@
 // Strideable Conformance
 //===----------------------------------------------------------------------===//
 
-@_transparent extension CGFloat : Strideable {
+extension CGFloat : Strideable {
     /// Returns a stride `x` such that `self.advanced(by: x)` approximates
     /// `other`.
     ///
@@ -571,41 +632,35 @@
 // Deprecated operators
 //===----------------------------------------------------------------------===//
 
-@_transparent
 @available(*, unavailable, message: "use += 1")
 @discardableResult
 public prefix func ++(rhs: inout CGFloat) -> CGFloat {
     fatalError("++ is not available")
 }
 
-@_transparent
 @available(*, unavailable, message: "use -= 1")
 @discardableResult
 public prefix func --(rhs: inout CGFloat) -> CGFloat {
     fatalError("-- is not available")
 }
 
-@_transparent
 @available(*, unavailable, message: "use += 1")
 @discardableResult
 public postfix func ++(lhs: inout CGFloat) -> CGFloat {
     fatalError("++ is not available")
 }
 
-@_transparent
 @available(*, unavailable, message: "use -= 1")
 @discardableResult
 public postfix func --(lhs: inout CGFloat) -> CGFloat {
     fatalError("-- is not available")
 }
 
-@_transparent
 @available(*, unavailable, message: "Use truncatingRemainder instead")
 public func %(lhs: CGFloat, rhs: CGFloat) -> CGFloat {
     fatalError("% is not available.")
 }
 
-@_transparent
 @available(*, unavailable, message: "Use formTruncatingRemainder instead")
 public func %=(lhs: inout CGFloat, rhs: CGFloat) {
     fatalError("%= is not available.")
@@ -880,16 +935,17 @@
     return CGFloat(yn(n, Double(x.native)))
 }
 
-@_transparent
 extension CGFloat : _CVarArgPassedAsDouble, _CVarArgAligned {
     /// Transform `self` into a series of machine words that can be
     /// appropriately interpreted by C varargs
+    @_transparent
     public var _cVarArgEncoding: [Int] {
         return native._cVarArgEncoding
     }
     
     /// Return the required alignment in bytes of 
     /// the value returned by `_cVarArgEncoding`.
+    @_transparent
     public var _cVarArgAlignment: Int { 
         return native._cVarArgAlignment
     }
diff --git a/Foundation/CharacterSet.swift b/Foundation/CharacterSet.swift
index 4babf01..35fbe72 100644
--- a/Foundation/CharacterSet.swift
+++ b/Foundation/CharacterSet.swift
@@ -13,6 +13,10 @@
 private func _utfRangeToNSRange(_ inRange : Range<UnicodeScalar>) -> NSRange {
     return NSMakeRange(Int(inRange.lowerBound.value), Int(inRange.upperBound.value - inRange.lowerBound.value))
 }
+ 
+private func _utfRangeToNSRange(_ inRange : ClosedRange<UnicodeScalar>) -> NSRange {
+    return NSMakeRange(Int(inRange.lowerBound.value), Int(inRange.upperBound.value - inRange.lowerBound.value + 1))
+}
 
 internal final class _SwiftNSCharacterSet : NSCharacterSet, _SwiftNativeFoundationType {
     internal typealias ImmutableType = NSCharacterSet
@@ -129,8 +133,7 @@
     ///
     /// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired.
     public init(charactersIn range: ClosedRange<UnicodeScalar>) {
-        let halfOpenRange = range.lowerBound..<UnicodeScalar(range.upperBound.value + 1)!
-        _wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(range: _utfRangeToNSRange(halfOpenRange)))
+        _wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(range: _utfRangeToNSRange(range)))
     }
     
     /// Initialize with the characters in the given string.
@@ -320,8 +323,7 @@
     ///
     /// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired.
     public mutating func insert(charactersIn range: ClosedRange<UnicodeScalar>) {
-        let halfOpenRange = range.lowerBound..<UnicodeScalar(range.upperBound.value + 1)!
-        let nsRange = _utfRangeToNSRange(halfOpenRange)
+        let nsRange = _utfRangeToNSRange(range)
         _applyUnmanagedMutation {
             $0.addCharacters(in: nsRange)
         }
@@ -337,8 +339,7 @@
     
     /// Remove a closed range of integer values from the `CharacterSet`.
     public mutating func remove(charactersIn range: ClosedRange<UnicodeScalar>) {
-        let halfOpenRange = range.lowerBound..<UnicodeScalar(range.upperBound.value + 1)!
-        let nsRange = _utfRangeToNSRange(halfOpenRange)
+        let nsRange = _utfRangeToNSRange(range)
         _applyUnmanagedMutation {
             $0.removeCharacters(in: nsRange)
         }
diff --git a/Foundation/NSCFString.swift b/Foundation/NSCFString.swift
index e12e0fa..4558549 100644
--- a/Foundation/NSCFString.swift
+++ b/Foundation/NSCFString.swift
@@ -140,19 +140,18 @@
 }
 
 internal func _CFSwiftStringGetBytes(_ str: AnyObject, encoding: CFStringEncoding, range: CFRange, buffer: UnsafeMutablePointer<UInt8>?, maxBufLen: CFIndex, usedBufLen: UnsafeMutablePointer<CFIndex>?) -> CFIndex {
+    let convertedLength: CFIndex
     switch encoding {
         // TODO: Don't treat many encodings like they are UTF8
     case CFStringEncoding(kCFStringEncodingUTF8), CFStringEncoding(kCFStringEncodingISOLatin1), CFStringEncoding(kCFStringEncodingMacRoman), CFStringEncoding(kCFStringEncodingASCII), CFStringEncoding(kCFStringEncodingNonLossyASCII):
-        let encodingView = (str as! NSString)._swiftObject.utf8
-        let start = encodingView.startIndex
+        let encodingView = (str as! NSString).substring(with: NSRange(range)).utf8
         if let buffer = buffer {
-            for idx in 0..<range.length {
-                let characterIndex = encodingView.index(start, offsetBy: idx + range.location)
-                let character = encodingView[characterIndex]
+            for (idx, character) in encodingView.enumerated() {
                 buffer.advanced(by: idx).initialize(to: character)
             }
         }
-        usedBufLen?.pointee = range.length
+        usedBufLen?.pointee = encodingView.count
+        convertedLength = encodingView.count
         
     case CFStringEncoding(kCFStringEncodingUTF16):
         let encodingView = (str as! NSString)._swiftObject.utf16
@@ -169,13 +168,13 @@
         }
         // Every character was 2 bytes
         usedBufLen?.pointee = range.length * 2
-
+        convertedLength = range.length
 
     default:
         fatalError("Attempted to get bytes of a Swift string using an unsupported encoding")
     }
     
-    return range.length
+    return convertedLength
 }
 
 internal func _CFSwiftStringCreateWithSubstring(_ str: AnyObject, range: CFRange) -> Unmanaged<AnyObject> {
diff --git a/Foundation/NSData.swift b/Foundation/NSData.swift
index 7c368a2..80a07fa 100644
--- a/Foundation/NSData.swift
+++ b/Foundation/NSData.swift
@@ -217,7 +217,12 @@
     }
     
     open var bytes: UnsafeRawPointer {
-        return UnsafeRawPointer(CFDataGetBytePtr(_cfObject))
+        guard let bytePtr = CFDataGetBytePtr(_cfObject) else {
+            //This could occure on empty data being encoded.
+            //TODO: switch with nil when signature is fixed
+            return UnsafeRawPointer(bitPattern: 0xf00deadb0c0)! //would not result in 'nil unwrapped optional'
+        }
+        return UnsafeRawPointer(bytePtr)
     }
 
     
diff --git a/Foundation/NSDecimalNumber.swift b/Foundation/NSDecimalNumber.swift
index a8b1db4..46b9b20 100644
--- a/Foundation/NSDecimalNumber.swift
+++ b/Foundation/NSDecimalNumber.swift
@@ -104,11 +104,41 @@
         self.decimal = dcm
         super.init()
     }
-    public convenience init(string numberValue: String?) { NSUnimplemented() }
-    public convenience init(string numberValue: String?, locale: AnyObject?) { NSUnimplemented() }
+    public convenience init(string numberValue: String?) {
+        self.init(decimal: Decimal(string: numberValue ?? "") ?? Decimal.nan)
+    }
+    public convenience init(string numberValue: String?, locale: AnyObject?) {
+        self.init(decimal: Decimal(string: numberValue ?? "", locale: locale as? Locale) ?? Decimal.nan)
+    }
 
-    public required init?(coder aDecoder: NSCoder) {
-        NSUnimplemented()
+    public required init?(coder: NSCoder) {
+        guard coder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        let exponent:Int32 = coder.decodeInt32(forKey: "NS.exponent")
+        let length:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.length"))
+        let isNegative:UInt32 = UInt32(coder.decodeBool(forKey: "NS.negative") ? 1 : 0)
+        let isCompact:UInt32 = UInt32(coder.decodeBool(forKey: "NS.compact") ? 1 : 0)
+        // let byteOrder:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.bo"))
+        guard let mantissaData: Data = coder.decodeObject(forKey: "NS.mantissa") as? Data else {
+            return nil // raise "Critical NSDecimalNumber archived data is missing"
+        }
+        guard mantissaData.count == Int(NSDecimalMaxSize * 2) else {
+            return nil  // raise "Critical NSDecimalNumber archived data is wrong size"
+        }
+        // Byte order?
+        let mantissa:(UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) = (
+            UInt16(mantissaData[0]) << 8 & UInt16(mantissaData[1]),
+            UInt16(mantissaData[2]) << 8 & UInt16(mantissaData[3]),
+            UInt16(mantissaData[4]) << 8 & UInt16(mantissaData[5]),
+            UInt16(mantissaData[6]) << 8 & UInt16(mantissaData[7]),
+            UInt16(mantissaData[8]) << 8 & UInt16(mantissaData[9]),
+            UInt16(mantissaData[10]) << 8 & UInt16(mantissaData[11]),
+            UInt16(mantissaData[12]) << 8 & UInt16(mantissaData[13]),
+            UInt16(mantissaData[14]) << 8 & UInt16(mantissaData[15])
+        )
+        self.decimal = Decimal(_exponent: exponent, _length: length, _isNegative: isNegative, _isCompact: isCompact, _reserved: 0, _mantissa: mantissa)
+        super.init()
     }
 
     public required convenience init(floatLiteral value: Double) {
@@ -251,8 +281,11 @@
     //   scale: No defined scale (full precision)
     //   ignore exactnessException
     //   raise on overflow, underflow and divide by zero.
-    
-    open override var objCType: UnsafePointer<Int8> { NSUnimplemented() }
+    static let OBJC_TYPE = "d".utf8CString
+
+    open override var objCType: UnsafePointer<Int8> {
+        return NSDecimalNumber.OBJC_TYPE.withUnsafeBufferPointer{ $0.baseAddress! }
+    }
     // return 'd' for double
     
     open override var int8Value: Int8 {
@@ -330,12 +363,44 @@
         _raiseOnUnderflow = true
         _raiseOnDivideByZero = true
     }
-    public required init?(coder aDecoder: NSCoder) {
-        NSUnimplemented()
+    public required init?(coder: NSCoder) {
+        guard coder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        _roundingMode = NSDecimalNumber.RoundingMode(rawValue: UInt(coder.decodeInteger(forKey: "NS.roundingMode")))!
+        if coder.containsValue(forKey: "NS.scale") {
+            _scale = Int16(coder.decodeInteger(forKey: "NS.scale"))
+        } else {
+            _scale = Int16(NSDecimalNoScale)
+        }
+        _raiseOnExactness = coder.decodeBool(forKey: "NS.raise.exactness")
+        _raiseOnOverflow = coder.decodeBool(forKey: "NS.raise.overflow")
+        _raiseOnUnderflow = coder.decodeBool(forKey: "NS.raise.underflow")
+        _raiseOnDivideByZero = coder.decodeBool(forKey: "NS.raise.dividebyzero")
     }
     
-    open func encode(with aCoder: NSCoder) {
-        NSUnimplemented()
+    open func encode(with coder: NSCoder) {
+        guard coder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        if _roundingMode != .plain {
+            coder.encode(Int(_roundingMode.rawValue), forKey: "NS.roundingmode")
+        }
+        if _scale != Int16(NSDecimalNoScale) {
+            coder.encode(_scale, forKey:"NS.scale")
+        }
+        if _raiseOnExactness {
+            coder.encode(_raiseOnExactness, forKey:"NS.raise.exactness")
+        }
+        if _raiseOnOverflow {
+            coder.encode(_raiseOnOverflow, forKey:"NS.raise.overflow")
+        }
+        if _raiseOnUnderflow {
+            coder.encode(_raiseOnUnderflow, forKey:"NS.raise.underflow")
+        }
+        if _raiseOnDivideByZero {
+            coder.encode(_raiseOnDivideByZero, forKey:"NS.raise.dividebyzero")
+        }
     }
     
     open class func `default`() -> NSDecimalNumberHandler {
diff --git a/Foundation/NSFileHandle.swift b/Foundation/NSFileHandle.swift
index 8596e66..dcc3e5d 100644
--- a/Foundation/NSFileHandle.swift
+++ b/Foundation/NSFileHandle.swift
@@ -214,11 +214,49 @@
     open class var standardError: FileHandle {
         return _stderrFileHandle
     }
-    
+
+    internal static var _nulldeviceFileHandle: FileHandle = {
+        class NullDevice: FileHandle {
+            override var availableData: Data {
+                return Data()
+            }
+
+            override func readDataToEndOfFile() -> Data {
+                return Data()
+            }
+
+            override func readData(ofLength length: Int) -> Data {
+                return Data()
+            }
+
+            override func write(_ data: Data) {}
+
+            override var offsetInFile: UInt64 {
+                return 0
+            }
+
+            override func seekToEndOfFile() -> UInt64 {
+                return 0
+            }
+
+            override func seek(toFileOffset offset: UInt64) {}
+
+            override func truncateFile(atOffset offset: UInt64) {}
+
+            override func synchronizeFile() {}
+
+            override func closeFile() {}
+
+            deinit {}
+        }
+
+        return NullDevice(fileDescriptor: -1, closeOnDealloc: false)
+    }()
+
     open class var nullDevice: FileHandle {
-        NSUnimplemented()
+        return _nulldeviceFileHandle
     }
-    
+
     public convenience init?(forReadingAtPath path: String) {
         self.init(path: path, flags: O_RDONLY, createMode: 0)
     }
diff --git a/Foundation/NSHTTPCookie.swift b/Foundation/NSHTTPCookie.swift
index 7da3b6e..f78dd5d 100644
--- a/Foundation/NSHTTPCookie.swift
+++ b/Foundation/NSHTTPCookie.swift
@@ -593,6 +593,30 @@
     open var portList: [NSNumber]? {
         return _portList
     }
+
+    open override var description: String {
+        var str = "<\(type(of: self)) "
+        str += "version:\(self._version) name:\"\(self._name)\" value:\"\(self._value)\" expiresDate:"
+        if let expires = self._expiresDate {
+            str += "\(expires)"
+        } else {
+            str += "nil"
+        }
+        str += " sessionOnly:\(self._sessionOnly) domain:\"\(self._domain)\" path:\"\(self._path)\" isSecure:\(self._secure) comment:"
+        if let comments = self._comment {
+            str += "\(comments)"
+        } else {
+            str += "nil"
+        }
+        str += " ports:{ "
+        if let ports = self._portList {
+            str += "\(NSArray(array: (ports)).componentsJoined(by: ","))"
+        } else {
+            str += "0"
+        }
+        str += " }>"
+        return str
+    }
 }
 
 //utils for cookie parsing
diff --git a/Foundation/NSJSONSerialization.swift b/Foundation/NSJSONSerialization.swift
index 48f53b1..cd4aed7 100644
--- a/Foundation/NSJSONSerialization.swift
+++ b/Foundation/NSJSONSerialization.swift
@@ -101,14 +101,13 @@
     /* Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8.
      */
     internal class func _data(withJSONObject value: Any, options opt: WritingOptions, stream: Bool) throws -> Data {
-        var result = Data()
+        var jsonStr = String()
         
         var writer = JSONWriter(
             pretty: opt.contains(.prettyPrinted),
             writer: { (str: String?) in
                 if let str = str {
-                    let count = str.lengthOfBytes(using: .utf8)
-                    result.append(UnsafeRawPointer(str.cString(using: .utf8)!).bindMemory(to: UInt8.self, capacity: count), count: count)
+                    jsonStr.append(str)
                 }
             }
         )
@@ -131,6 +130,14 @@
             }
         }
         
+        let count = jsonStr.lengthOfBytes(using: .utf8)
+        let bufferLength = count+1 // Allow space for null terminator
+        var utf8: [CChar] = Array<CChar>(repeating: 0, count: bufferLength)
+        if !jsonStr.getCString(&utf8, maxLength: bufferLength, encoding: .utf8) {
+            fatalError("Failed to generate a CString from a String")
+        }
+        let rawBytes = UnsafeRawPointer(UnsafePointer(utf8))
+        let result = Data(bytes: rawBytes.bindMemory(to: UInt8.self, capacity: count), count: count)
         return result
     }
     open class func data(withJSONObject value: Any, options opt: WritingOptions = []) throws -> Data {
@@ -270,21 +277,21 @@
     }
     
     mutating func serializeJSON(_ obj: Any) throws {
-        
-        if let str = obj as? String {
+
+        switch (obj) {
+        case let str as String:
             try serializeString(str)
-        } else if let num = _SwiftValue.store(obj) as? NSNumber {
-            try serializeNumber(num)
-        } else if let array = obj as? Array<Any> {
+        case let boolValue as Bool:
+            serializeBool(boolValue)
+        case _ where _SwiftValue.store(obj) is NSNumber:
+            try serializeNumber(_SwiftValue.store(obj) as! NSNumber)
+        case let array as Array<Any>:
             try serializeArray(array)
-        } else if let dict = obj as? Dictionary<AnyHashable, Any> {
+        case let dict as Dictionary<AnyHashable, Any>:
             try serializeDictionary(dict)
-        } else if let null = obj as? NSNull {
+        case let null as NSNull:
             try serializeNull(null)
-        } else if let boolVal = obj as? Bool {
-            try serializeNumber(NSNumber(value: boolVal))
-        }
-        else {
+        default:
             throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "Invalid object cannot be serialized"])
         }
     }
@@ -319,15 +326,26 @@
         writer("\"")
     }
 
+    func serializeBool(_ bool: Bool) {
+        switch bool {
+        case true:
+            writer("true")
+        case false:
+            writer("false")
+        }
+    }
+
     mutating func serializeNumber(_ num: NSNumber) throws {
         if num.doubleValue.isInfinite || num.doubleValue.isNaN {
             throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "Number cannot be infinity or NaN"])
         }
         
-        // Cannot detect type information (e.g. bool) as there is no objCType property on NSNumber in Swift
-        // So, just print the number
-
-        writer(_serializationString(for: num))
+        switch num._objCType {
+        case .Bool:
+            serializeBool(num.boolValue)
+        default:
+            writer(_serializationString(for: num))
+        }
     }
 
     mutating func serializeArray(_ array: [Any]) throws {
diff --git a/Foundation/NSLock.swift b/Foundation/NSLock.swift
index c4a9f68..e166b80 100644
--- a/Foundation/NSLock.swift
+++ b/Foundation/NSLock.swift
@@ -115,7 +115,7 @@
 
     open func lock(before limit: Date) -> Bool {
         _cond.lock()
-        while _thread == nil {
+        while _thread != nil {
             if !_cond.wait(until: limit) {
                 _cond.unlock()
                 return false
diff --git a/Foundation/NSNotification.swift b/Foundation/NSNotification.swift
old mode 100755
new mode 100644
diff --git a/Foundation/NSNumber.swift b/Foundation/NSNumber.swift
index 14bec84..5f75de8 100644
--- a/Foundation/NSNumber.swift
+++ b/Foundation/NSNumber.swift
@@ -200,7 +200,9 @@
     // This layout MUST be the same as CFNumber so that they are bridgeable
     private var _base = _CFInfo(typeID: CFNumberGetTypeID())
     private var _pad: UInt64 = 0
-    
+
+    internal let _objCType: _NSSimpleObjCType
+
     internal var _cfObject: CFType {
         return unsafeBitCast(self, to: CFType.self)
     }
@@ -221,77 +223,95 @@
         }
         return false
     }
+
+    open override var objCType: UnsafePointer<Int8> {
+        return UnsafePointer<Int8>(bitPattern: UInt(_objCType.rawValue.value))!
+    }
     
     deinit {
         _CFDeinit(self)
     }
     
     public init(value: Int8) {
+        _objCType = .Char
         super.init()
         _CFNumberInitInt8(_cfObject, value)
     }
     
     public init(value: UInt8) {
+        _objCType = .UChar
         super.init()
         _CFNumberInitUInt8(_cfObject, value)
     }
     
     public init(value: Int16) {
+        _objCType = .Short
         super.init()
         _CFNumberInitInt16(_cfObject, value)
     }
     
     public init(value: UInt16) {
+        _objCType = .UShort
         super.init()
         _CFNumberInitUInt16(_cfObject, value)
     }
     
     public init(value: Int32) {
+        _objCType = .Long
         super.init()
         _CFNumberInitInt32(_cfObject, value)
     }
     
     public init(value: UInt32) {
+        _objCType = .ULong
         super.init()
         _CFNumberInitUInt32(_cfObject, value)
     }
     
     public init(value: Int) {
+        _objCType = .Int
         super.init()
         _CFNumberInitInt(_cfObject, value)
     }
     
     public init(value: UInt) {
+        _objCType = .UInt
         super.init()
         _CFNumberInitUInt(_cfObject, value)
     }
     
     public init(value: Int64) {
+        _objCType = .LongLong
         super.init()
         _CFNumberInitInt64(_cfObject, value)
     }
     
     public init(value: UInt64) {
+        _objCType = .ULongLong
         super.init()
         _CFNumberInitUInt64(_cfObject, value)
     }
     
     public init(value: Float) {
+        _objCType = .Float
         super.init()
         _CFNumberInitFloat(_cfObject, value)
     }
     
     public init(value: Double) {
+        _objCType = .Double
         super.init()
         _CFNumberInitDouble(_cfObject, value)
     }
     
     public init(value: Bool) {
+        _objCType = .Bool
         super.init()
         _CFNumberInitBool(_cfObject, value)
     }
 
     override internal init() {
+        _objCType = .Undef
         super.init()
     }
 
diff --git a/Foundation/NSNumberFormatter.swift b/Foundation/NSNumberFormatter.swift
index d0cf61e..fe319d1 100644
--- a/Foundation/NSNumberFormatter.swift
+++ b/Foundation/NSNumberFormatter.swift
@@ -70,6 +70,9 @@
             
             let obj = CFNumberFormatterCreate(kCFAllocatorSystemDefault, locale._cfObject, numberStyle)!
             _setFormatterAttributes(obj)
+            if let format = _format {
+                CFNumberFormatterSetFormat(obj, format._cfObject)
+            }
             _currentCfFormatter = obj
             return obj
         }
@@ -99,12 +102,13 @@
     open func number(from string: String) -> NSNumber? {
         var range = CFRange(location: 0, length: string.length)
         let number = withUnsafeMutablePointer(to: &range) { (rangePointer: UnsafeMutablePointer<CFRange>) -> NSNumber? in
-            
+
             #if os(OSX) || os(iOS)
-                let result = CFNumberFormatterCreateNumberFromString(kCFAllocatorSystemDefault, _cfFormatter, string._cfObject, rangePointer, CFNumberFormatterOptionFlags.parseIntegersOnly.rawValue)
+                let parseOption = allowsFloats ? 0 : CFNumberFormatterOptionFlags.parseIntegersOnly.rawValue
             #else
-                let result = CFNumberFormatterCreateNumberFromString(kCFAllocatorSystemDefault, _cfFormatter, string._cfObject, rangePointer, CFOptionFlags(kCFNumberFormatterParseIntegersOnly))
+                let parseOption = allowsFloats ? 0 : CFOptionFlags(kCFNumberFormatterParseIntegersOnly)
             #endif
+            let result = CFNumberFormatterCreateNumberFromString(kCFAllocatorSystemDefault, _cfFormatter, string._cfObject, rangePointer, parseOption)
 
             return result?._nsObject
         }
@@ -157,7 +161,7 @@
         _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPerMillSymbol, value: _percentSymbol?._cfObject)
         _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterInternationalCurrencySymbol, value: _internationalCurrencySymbol?._cfObject)
         _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyGroupingSeparator, value: _currencyGroupingSeparator?._cfObject)
-        _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterIsLenient, value: kCFBooleanTrue)
+        _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterIsLenient, value: _lenient._cfObject)
         _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterUseSignificantDigits, value: _usesSignificantDigits._cfObject)
         if _usesSignificantDigits {
             _setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinSignificantDigits, value: _minimumSignificantDigits._bridgeToObjectiveC()._cfObject)
@@ -182,7 +186,7 @@
             switch newValue {
             case .none, .ordinal, .spellOut:
                 _usesSignificantDigits = false
-                
+
             case .currency, .currencyPlural, .currencyISOCode, .currencyAccounting:
                 _usesSignificantDigits = false
                 _usesGroupingSeparator = true
@@ -838,10 +842,10 @@
     
     //
     
-    internal var _format: String = "#;0;#"
+    internal var _format: String?
     open var format: String {
         get {
-            return _format
+            return _format ?? "#;0;#"
         }
         set {
             _reset()
diff --git a/Foundation/NSPredicate.swift b/Foundation/NSPredicate.swift
index 083782b..3aada9c 100644
--- a/Foundation/NSPredicate.swift
+++ b/Foundation/NSPredicate.swift
@@ -15,8 +15,8 @@
     private enum PredicateKind {
         case boolean(Bool)
         case block((Any?, [String : Any]?) -> Bool)
-        // TODO: case for init(format:argumentArray:)
-        // TODO: case for init(fromMetadataQueryString:)
+        case format(String)
+        case metadataQuery(String)
     }
 
     private let kind: PredicateKind
@@ -26,11 +26,33 @@
     }
     
     public required init?(coder aDecoder: NSCoder) {
-        NSUnimplemented()
+        guard aDecoder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        
+        let encodedBool = aDecoder.decodeBool(forKey: "NS.boolean.value")
+        self.kind = .boolean(encodedBool)
+        
+        super.init()
     }
     
     open func encode(with aCoder: NSCoder) {
-        NSUnimplemented()
+        guard aCoder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        
+        //TODO: store kind key for .boolean, .format, .metadataQuery
+        
+        switch self.kind {
+        case .boolean(let value):
+            aCoder.encode(value, forKey: "NS.boolean.value")
+        case .block:
+            preconditionFailure("NSBlockPredicate cannot be encoded or decoded.")
+        case .format:
+            NSUnimplemented()
+        case .metadataQuery:
+            NSUnimplemented()
+        }
     }
     
     open override func copy() -> Any {
@@ -38,7 +60,38 @@
     }
     
     open func copy(with zone: NSZone? = nil) -> Any {
-        NSUnimplemented()
+        switch self.kind {
+        case .boolean(let value):
+            return NSPredicate(value: value)
+        case .block(let block):
+            return NSPredicate(block: block)
+        case .format:
+            NSUnimplemented()
+        case .metadataQuery:
+            NSUnimplemented()
+        }
+    }
+    
+    open override func isEqual(_ object: Any?) -> Bool {
+        if let other = object as? NSPredicate {
+            if other === self {
+                return true
+            } else {
+                switch (other.kind, self.kind) {
+                case (.boolean(let otherBool), .boolean(let selfBool)):
+                    return otherBool == selfBool
+                case (.format, .format):
+                    NSUnimplemented()
+                case (.metadataQuery, .metadataQuery):
+                    NSUnimplemented()
+                default:
+                    // NSBlockPredicate returns false even for copy
+                    return false
+                }
+            }
+        }
+        
+        return false
     }
     
     // Parse predicateFormat and return an appropriate predicate
@@ -58,7 +111,21 @@
         super.init()
     }
     
-    open var predicateFormat: String  { NSUnimplemented() } // returns the format string of the predicate
+    open var predicateFormat: String {
+        switch self.kind {
+        case .boolean(let value):
+            return value ? "TRUEPREDICATE" : "FALSEPREDICATE"
+        case .block:
+            // TODO: Bring NSBlockPredicate's predicateFormat to macOS's Foundation version
+            // let address = unsafeBitCast(block, to: Int.self)
+            // return String(format:"BLOCKPREDICATE(%2X)", address)
+            return "BLOCKPREDICATE"
+        case .format:
+            NSUnimplemented()
+        case .metadataQuery:
+            NSUnimplemented()
+        }
+    }
     
     open func withSubstitutionVariables(_ variables: [String : Any]) -> Self { NSUnimplemented() } // substitute constant values for variables
     
@@ -76,6 +143,10 @@
             return value
         case let .block(block):
             return block(object, bindings)
+        case .format:
+            NSUnimplemented()
+        case .metadataQuery:
+            NSUnimplemented()
         }
     } // single pass evaluation substituting variables from the bindings dictionary for any variable expressions encountered
     
diff --git a/Foundation/NSPropertyList.swift b/Foundation/NSPropertyList.swift
index 7ea248a..5141c42 100644
--- a/Foundation/NSPropertyList.swift
+++ b/Foundation/NSPropertyList.swift
@@ -44,10 +44,11 @@
 #else
         let fmt = CFPropertyListFormat(format.rawValue)
 #endif
-        return CFPropertyListIsValid(unsafeBitCast(_SwiftValue.store(plist), to: CFPropertyList.self), fmt)
+        let plistObj = _SwiftValue.store(plist)
+        return CFPropertyListIsValid(plistObj, fmt)
     }
-    
-    open class func data(fromPropertyList plist: AnyObject, format: PropertyListFormat, options opt: WriteOptions) throws -> Data {
+
+    open class func data(fromPropertyList plist: Any, format: PropertyListFormat, options opt: WriteOptions) throws -> Data {
         var error: Unmanaged<CFError>? = nil
         let result = withUnsafeMutablePointer(to: &error) { (outErr: UnsafeMutablePointer<Unmanaged<CFError>?>) -> CFData? in
 #if os(OSX) || os(iOS)
@@ -56,7 +57,8 @@
             let fmt = CFPropertyListFormat(format.rawValue)
 #endif
             let options = CFOptionFlags(opt)
-            return CFPropertyListCreateData(kCFAllocatorSystemDefault, plist, fmt, options, outErr)
+            let plistObj = _SwiftValue.store(plist)
+            return CFPropertyListCreateData(kCFAllocatorSystemDefault, plistObj, fmt, options, outErr)
         }
         if let res = result {
             return res._swiftObject
@@ -64,7 +66,7 @@
             throw error!.takeRetainedValue()._nsObject
         }
     }
-    
+
     /// - 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
diff --git a/Foundation/NSString.swift b/Foundation/NSString.swift
index 32455e9..95f5e6c 100644
--- a/Foundation/NSString.swift
+++ b/Foundation/NSString.swift
@@ -817,7 +817,7 @@
 
             return data
         }
-        return nil
+        return Data()
     }
     
     public func data(using encoding: UInt) -> Data? {
@@ -1008,8 +1008,10 @@
     open func trimmingCharacters(in set: CharacterSet) -> String {
         let len = length
         var buf = _NSStringBuffer(string: self, start: 0, end: len)
-        while !buf.isAtEnd && set.contains(UnicodeScalar(buf.currentCharacter)!) {
-            buf.advance()
+        while !buf.isAtEnd,
+            let character = UnicodeScalar(buf.currentCharacter),
+            set.contains(character) {
+                buf.advance()
         }
         
         let startOfNonTrimmedRange = buf.location // This points at the first char not in the set
@@ -1018,8 +1020,10 @@
             return ""
         } else if startOfNonTrimmedRange < len - 1 {
             buf.location = len - 1
-            while set.contains(UnicodeScalar(buf.currentCharacter)!) && buf.location >= startOfNonTrimmedRange {
-                buf.rewind()
+            while let character = UnicodeScalar(buf.currentCharacter),
+                set.contains(character),
+                buf.location >= startOfNonTrimmedRange {
+                    buf.rewind()
             }
             let endOfNonTrimmedRange = buf.location
             return substring(with: NSMakeRange(startOfNonTrimmedRange, endOfNonTrimmedRange + 1 - startOfNonTrimmedRange))
diff --git a/Foundation/NSURLCredential.swift b/Foundation/NSURLCredential.swift
index 300126a..32cd075 100644
--- a/Foundation/NSURLCredential.swift
+++ b/Foundation/NSURLCredential.swift
@@ -65,11 +65,32 @@
      */
     
     public required init?(coder aDecoder: NSCoder) {
-        NSUnimplemented()
+        guard aDecoder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        
+        func bridgeString(_ value: NSString) -> String? {
+            return String._unconditionallyBridgeFromObjectiveC(value)
+        }
+        
+        let encodedUser = aDecoder.decodeObject(forKey: "NS._user") as! NSString
+        self._user = bridgeString(encodedUser)!
+        
+        let encodedPassword = aDecoder.decodeObject(forKey: "NS._password") as! NSString
+        self._password = bridgeString(encodedPassword)!
+        
+        let encodedPersistence = aDecoder.decodeObject(forKey: "NS._persistence") as! NSNumber
+        self._persistence = Persistence(rawValue: encodedPersistence.uintValue)!
     }
     
     open func encode(with aCoder: NSCoder) {
-        NSUnimplemented()
+        guard aCoder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        
+        aCoder.encode(self._user._bridgeToObjectiveC(), forKey: "NS._user")
+        aCoder.encode(self._password._bridgeToObjectiveC(), forKey: "NS._password")
+        aCoder.encode(self._persistence.rawValue._bridgeToObjectiveC(), forKey: "NS._persistence")
     }
     
     static public var supportsSecureCoding: Bool {
@@ -84,6 +105,17 @@
         return self 
     }
     
+    open override func isEqual(_ object: Any?) -> Bool {
+        if let other = object as? URLCredential {
+            return other === self
+                || (other._user == self._user
+                    && other._password == self._password
+                    && other._persistence == self._persistence)
+        }
+        
+        return false
+    }
+    
     /*!
         @method persistence
         @abstract Determine whether this credential is or should be stored persistently
diff --git a/Foundation/NSURLRequest.swift b/Foundation/NSURLRequest.swift
index 7081e0f..a044297 100644
--- a/Foundation/NSURLRequest.swift
+++ b/Foundation/NSURLRequest.swift
@@ -156,11 +156,101 @@
     }
     
     public required init?(coder aDecoder: NSCoder) {
-        NSUnimplemented()
+        guard aDecoder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        
+        if let encodedURL = aDecoder.decodeObject(forKey: "NS.url") as? NSURL {
+            self.url = encodedURL._swiftObject
+        }
+        
+        if let encodedHeaders = aDecoder.decodeObject(forKey: "NS._allHTTPHeaderFields") as? NSDictionary {
+            self._allHTTPHeaderFields = encodedHeaders.reduce([String : String]()) { result, item in
+                var result = result
+                if let key = item.key as? NSString,
+                    let value = item.value as? NSString {
+                    result[key._swiftObject] = value._swiftObject
+                }
+                return result
+            }
+        }
+        
+        if let encodedDocumentURL = aDecoder.decodeObject(forKey: "NS.mainDocumentURL") as? NSURL {
+            self.mainDocumentURL = encodedDocumentURL._swiftObject
+        }
+        
+        if let encodedMethod = aDecoder.decodeObject(forKey: "NS.httpMethod") as? NSString {
+            self.httpMethod = encodedMethod._swiftObject
+        }
+        
+        let encodedCachePolicy = aDecoder.decodeObject(forKey: "NS._cachePolicy") as! NSNumber
+        self._cachePolicy = CachePolicy(rawValue: encodedCachePolicy.uintValue)!
+        
+        let encodedTimeout = aDecoder.decodeObject(forKey: "NS._timeoutInterval") as! NSNumber
+        self._timeoutInterval = encodedTimeout.doubleValue
+
+        let encodedHttpBody: Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.httpBody") {
+            guard let buffer = $0 else { return nil }
+            return Data(buffer: buffer)
+        }
+        
+        if let encodedHttpBody = encodedHttpBody {
+            self._body = .data(encodedHttpBody)
+        }
+        
+        let encodedNetworkServiceType = aDecoder.decodeObject(forKey: "NS._networkServiceType") as! NSNumber
+        self._networkServiceType = NetworkServiceType(rawValue: encodedNetworkServiceType.uintValue)!
+        
+        let encodedCellularAccess = aDecoder.decodeObject(forKey: "NS._allowsCellularAccess") as! NSNumber
+        self._allowsCellularAccess = encodedCellularAccess.boolValue
+        
+        let encodedHandleCookies = aDecoder.decodeObject(forKey: "NS._httpShouldHandleCookies") as! NSNumber
+        self._httpShouldHandleCookies = encodedHandleCookies.boolValue
+        
+        let encodedUsePipelining = aDecoder.decodeObject(forKey: "NS._httpShouldUsePipelining") as! NSNumber
+        self._httpShouldUsePipelining = encodedUsePipelining.boolValue
     }
     
     open func encode(with aCoder: NSCoder) {
-        NSUnimplemented()
+        guard aCoder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        
+        aCoder.encode(self.url?._bridgeToObjectiveC(), forKey: "NS.url")
+        aCoder.encode(self._allHTTPHeaderFields?._bridgeToObjectiveC(), forKey: "NS._allHTTPHeaderFields")
+        aCoder.encode(self.mainDocumentURL?._bridgeToObjectiveC(), forKey: "NS.mainDocumentURL")
+        aCoder.encode(self.httpMethod?._bridgeToObjectiveC(), forKey: "NS.httpMethod")
+        aCoder.encode(self._cachePolicy.rawValue._bridgeToObjectiveC(), forKey: "NS._cachePolicy")
+        aCoder.encode(self._timeoutInterval._bridgeToObjectiveC(), forKey: "NS._timeoutInterval")
+        if let httpBody = self.httpBody?._bridgeToObjectiveC() {
+            let bytePtr = httpBody.bytes.bindMemory(to: UInt8.self, capacity: httpBody.length)
+            aCoder.encodeBytes(bytePtr, length: httpBody.length, forKey: "NS.httpBody")
+        }
+        //On macOS input stream is not encoded.
+        aCoder.encode(self._networkServiceType.rawValue._bridgeToObjectiveC(), forKey: "NS._networkServiceType")
+        aCoder.encode(self._allowsCellularAccess._bridgeToObjectiveC(), forKey: "NS._allowsCellularAccess")
+        aCoder.encode(self._httpShouldHandleCookies._bridgeToObjectiveC(), forKey: "NS._httpShouldHandleCookies")
+        aCoder.encode(self._httpShouldUsePipelining._bridgeToObjectiveC(), forKey: "NS._httpShouldUsePipelining")
+    }
+    
+    open override func isEqual(_ object: Any?) -> Bool {
+        //On macOS this fields do not determine the result:
+        //allHTTPHeaderFields
+        //timeoutInterval
+        //httBody
+        //networkServiceType
+        //httpShouldUsePipelining
+        if let other = object as? NSURLRequest {
+            return other === self
+                || (other.url == self.url
+                    && other.mainDocumentURL == self.mainDocumentURL
+                    && other.httpMethod == self.httpMethod
+                    && other._cachePolicy == self._cachePolicy
+                    && other.httpBodyStream == self.httpBodyStream
+                    && other._allowsCellularAccess == self._allowsCellularAccess
+                    && other._httpShouldHandleCookies == self._httpShouldHandleCookies)
+        }
+        return false
     }
     
     /// Indicates that NSURLRequest implements the NSSecureCoding protocol.
@@ -289,7 +379,7 @@
 /// example.
 open class NSMutableURLRequest : NSURLRequest {
     public required init?(coder aDecoder: NSCoder) {
-        NSUnimplemented()
+        super.init(coder: aDecoder)
     }
     
     public convenience init(url: URL) {
diff --git a/Foundation/NSURLResponse.swift b/Foundation/NSURLResponse.swift
index e74f9f1..e39bfcf 100644
--- a/Foundation/NSURLResponse.swift
+++ b/Foundation/NSURLResponse.swift
@@ -23,11 +23,39 @@
     }
     
     public required init?(coder aDecoder: NSCoder) {
-        NSUnimplemented()
+        guard aDecoder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        
+        if let encodedUrl = aDecoder.decodeObject(forKey: "NS.url") as? NSURL {
+            self.url = encodedUrl._swiftObject
+        }
+        
+        if let encodedMimeType = aDecoder.decodeObject(forKey: "NS.mimeType") as? NSString {
+            self.mimeType = encodedMimeType._swiftObject
+        }
+        
+        self.expectedContentLength = aDecoder.decodeInt64(forKey: "NS.expectedContentLength")
+        
+        if let encodedEncodingName = aDecoder.decodeObject(forKey: "NS.textEncodingName") as? NSString {
+            self.textEncodingName = encodedEncodingName._swiftObject
+        }
+        
+        if let encodedFilename = aDecoder.decodeObject(forKey: "NS.suggestedFilename") as? NSString {
+            self.suggestedFilename = encodedFilename._swiftObject
+        }
     }
     
     open func encode(with aCoder: NSCoder) {
-        NSUnimplemented()
+        guard aCoder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        
+        aCoder.encode(self.url?._bridgeToObjectiveC(), forKey: "NS.url")
+        aCoder.encode(self.mimeType?._bridgeToObjectiveC(), forKey: "NS.mimeType")
+        aCoder.encode(self.expectedContentLength, forKey: "NS.expectedContentLength")
+        aCoder.encode(self.textEncodingName?._bridgeToObjectiveC(), forKey: "NS.textEncodingName")
+        aCoder.encode(self.suggestedFilename?._bridgeToObjectiveC(), forKey: "NS.suggestedFilename")
     }
     
     open override func copy() -> Any {
@@ -135,7 +163,27 @@
     }
     
     public required init?(coder aDecoder: NSCoder) {
-        NSUnimplemented()
+        guard aDecoder.allowsKeyedCoding else {
+            preconditionFailure("Unkeyed coding is unsupported.")
+        }
+        
+        self.statusCode = aDecoder.decodeInteger(forKey: "NS.statusCode")
+        
+        if let encodedHeaders = aDecoder.decodeObject(forKey: "NS.allHeaderFields") as? NSDictionary {
+            self.allHeaderFields = encodedHeaders._swiftObject
+        } else {
+            self.allHeaderFields = [:]
+        }
+        
+        super.init(coder: aDecoder)
+    }
+    
+    open override func encode(with aCoder: NSCoder) {
+        super.encode(with: aCoder) //Will fail if .allowsKeyedCoding == false
+        
+        aCoder.encode(self.statusCode, forKey: "NS.statusCode")
+        aCoder.encode(self.allHeaderFields._bridgeToObjectiveC(), forKey: "NS.allHeaderFields")
+        
     }
     
     /// The HTTP status code of the receiver.
diff --git a/Foundation/NSURLSession/HTTPMessage.swift b/Foundation/NSURLSession/HTTPMessage.swift
index 4f41eef..6598d06 100644
--- a/Foundation/NSURLSession/HTTPMessage.swift
+++ b/Foundation/NSURLSession/HTTPMessage.swift
@@ -143,7 +143,12 @@
     var headersAsDictionary: [String: String] {
         var result: [String: String] = [:]
         headers.forEach {
-            result[$0.name] = $0.value
+            if result[$0.name] == nil {
+                result[$0.name] = $0.value
+            }
+            else {
+                result[$0.name]! += (", " + $0.value)
+            }
         }
         return result
     }
@@ -287,8 +292,13 @@
         var value: String?
         let line = headView[headView.index(after: nameRange.upperBound)..<headView.endIndex]
         if !line.isEmpty {
-            guard let v = line.trimSPHTPrefix else { return nil }
-            value = String(v)
+            if line.hasSPHTPrefix && line.count == 1 {
+                // to handle empty headers i.e header without value
+                value = String("")
+            } else {
+                guard let v = line.trimSPHTPrefix else { return nil }
+                value = String(v)
+            }
         }
         do {
             var t = tail
diff --git a/Foundation/NSURLSession/NSURLSessionTask.swift b/Foundation/NSURLSession/NSURLSessionTask.swift
index f8b9569..27ad59f 100644
--- a/Foundation/NSURLSession/NSURLSessionTask.swift
+++ b/Foundation/NSURLSession/NSURLSessionTask.swift
@@ -88,7 +88,7 @@
         originalRequest = nil
         body = .none
         workQueue = DispatchQueue(label: "URLSessionTask.notused.0")
-        taskAttributesIsolation = DispatchQueue(label: "URLSessionTask.notused.1")
+        taskAttributesIsolation = DispatchQueue(label: "URLSessionTask.notused.1", attributes: DispatchQueue.Attributes.concurrent)
         let fileName = NSTemporaryDirectory() + NSUUID().uuidString + ".tmp"
         _ = FileManager.default.createFile(atPath: fileName, contents: nil)
         self.tempFileURL = URL(fileURLWithPath: fileName)
@@ -145,7 +145,7 @@
             return r
         }
         //TODO: dispatch_barrier_async
-        set { taskAttributesIsolation.async { self._currentRequest = newValue } }
+        set { taskAttributesIsolation.async(flags: .barrier) { self._currentRequest = newValue } }
     }
     fileprivate var _currentRequest: URLRequest? = nil
     /*@NSCopying*/ open fileprivate(set) var response: URLResponse? {
@@ -154,7 +154,7 @@
             taskAttributesIsolation.sync { r = self._response }
             return r
         }
-        set { taskAttributesIsolation.async { self._response = newValue } }
+        set { taskAttributesIsolation.async(flags: .barrier) { self._response = newValue } }
     }
     fileprivate var _response: URLResponse? = nil
     
@@ -170,7 +170,7 @@
             taskAttributesIsolation.sync { r = self._countOfBytesReceived }
             return r
         }
-        set { taskAttributesIsolation.async { self._countOfBytesReceived = newValue } }
+        set { taskAttributesIsolation.async(flags: .barrier) { self._countOfBytesReceived = newValue } }
     }
     fileprivate var _countOfBytesReceived: Int64 = 0
     
@@ -181,7 +181,7 @@
             taskAttributesIsolation.sync { r = self._countOfBytesSent }
             return r
         }
-        set { taskAttributesIsolation.async { self._countOfBytesSent = newValue } }
+        set { taskAttributesIsolation.async(flags: .barrier) { self._countOfBytesSent = newValue } }
     }
 
     fileprivate var _countOfBytesSent: Int64 = 0
@@ -213,7 +213,7 @@
             taskAttributesIsolation.sync { r = self._state }
             return r
         }
-        set { taskAttributesIsolation.async { self._state = newValue } }
+        set { taskAttributesIsolation.async(flags: .barrier) { self._state = newValue } }
     }
     fileprivate var _state: URLSessionTask.State = .suspended
     
@@ -298,7 +298,7 @@
             return r
         }
         set {
-            taskAttributesIsolation.async { self._priority = newValue }
+            taskAttributesIsolation.async(flags: .barrier) { self._priority = newValue }
         }
     }
     fileprivate var _priority: Float = URLSessionTaskPriorityDefault
@@ -791,7 +791,7 @@
         // to the delegate. But in case of redirects etc. we might send another
         // request.
         guard case .transferInProgress(let ts) = internalState else { fatalError("Transfer completed, but it wasn't in progress.") }
-        guard let request = currentRequest else { fatalError("Transfer completed, but there's no currect request.") }
+        guard let request = currentRequest else { fatalError("Transfer completed, but there's no current request.") }
         guard errorCode == nil else {
             internalState = .transferFailed
             failWith(errorCode: errorCode!, request: request)
diff --git a/Foundation/Notification.swift b/Foundation/Notification.swift
index 2ed74d0..d929dbe 100644
--- a/Foundation/Notification.swift
+++ b/Foundation/Notification.swift
@@ -76,7 +76,17 @@
 
 extension Notification : CustomReflectable {
     public var customMirror: Mirror {
-        NSUnimplemented()
+        var children: [(label: String?, value: Any)] = [(label: "name", self.name.rawValue)]
+
+        if let object = self.object {
+            children.append((label: "object", object))
+        }
+
+        if let info = self.userInfo {
+            children.append((label: "userInfo", info))
+        }
+
+        return Mirror(self, children: children, displayStyle: .class)
     }
 }
 
diff --git a/TestFoundation/TestNSArray.swift b/TestFoundation/TestNSArray.swift
index 132747b..c905e52 100644
--- a/TestFoundation/TestNSArray.swift
+++ b/TestFoundation/TestNSArray.swift
@@ -500,7 +500,7 @@
     }
     
     private func createTestFile(_ path: String, _contents: Data) -> String? {
-        let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().uuidString + "/"
+        let tempDir = NSTemporaryDirectory() + "TestFoundation_Playground_" + NSUUID().uuidString + "/"
         do {
             try FileManager.default.createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
             if FileManager.default.createFile(atPath: tempDir + "/" + path, contents: _contents, attributes: nil) {
diff --git a/TestFoundation/TestNSBundle.swift b/TestFoundation/TestNSBundle.swift
index e427992..8e40179 100644
--- a/TestFoundation/TestNSBundle.swift
+++ b/TestFoundation/TestNSBundle.swift
@@ -108,7 +108,7 @@
     
     private func _setupPlayground() -> String? {
         // Make sure the directory is uniquely named
-        let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().uuidString + "/"
+        let tempDir = NSTemporaryDirectory() + "TestFoundation_Playground_" + NSUUID().uuidString + "/"
         
         do {
             try FileManager.default.createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
@@ -179,7 +179,7 @@
     }
     
     func test_bundleWithInvalidPath(){
-        let bundleInvalid = Bundle(path: "/tmp/test.playground")
+        let bundleInvalid = Bundle(path: NSTemporaryDirectory() + "test.playground")
         XCTAssertNil(bundleInvalid)
     }
     
diff --git a/TestFoundation/TestNSCharacterSet.swift b/TestFoundation/TestNSCharacterSet.swift
index 71ff177..7bd9d62 100644
--- a/TestFoundation/TestNSCharacterSet.swift
+++ b/TestFoundation/TestNSCharacterSet.swift
@@ -28,7 +28,7 @@
             ("testRanges", testRanges),
             ("testInsertAndRemove", testInsertAndRemove),
             ("testBasics", testBasics),
-            
+            ("testClosedRanges_SR_2988", testClosedRanges_SR_2988),
             ("test_Predefines", test_Predefines),
             ("test_Range", test_Range),
             ("test_String", test_String),
@@ -223,6 +223,18 @@
         }
     }
     
+    func testClosedRanges_SR_2988() {
+        // "CharacterSet.insert(charactersIn: ClosedRange) crashes on a closed ClosedRange<UnicodeScalar> containing U+D7FF"
+        let problematicChar = UnicodeScalar(0xD7FF)!
+        let range = capitalA...problematicChar
+        var characters = CharacterSet(charactersIn: range) // this should not crash
+        XCTAssertTrue(characters.contains(problematicChar))
+        characters.remove(charactersIn: range) // this should not crash
+        XCTAssertTrue(!characters.contains(problematicChar))
+        characters.insert(charactersIn: range) // this should not crash
+        XCTAssertTrue(characters.contains(problematicChar))
+    }
+    
     func test_Bitmap() {
         
     }
diff --git a/TestFoundation/TestNSData.swift b/TestFoundation/TestNSData.swift
index 9705c15..44daab7 100644
--- a/TestFoundation/TestNSData.swift
+++ b/TestFoundation/TestNSData.swift
@@ -89,6 +89,7 @@
             ("test_replaceBytes", test_replaceBytes),
             ("test_initDataWithCapacity", test_initDataWithCapacity),
             ("test_initDataWithCount", test_initDataWithCount),
+            ("test_emptyStringToData", test_emptyStringToData),
         ]
     }
     
@@ -438,6 +439,11 @@
             return
         }
     }
+
+    func test_emptyStringToData() {
+        let data = "".data(using: .utf8)!
+        XCTAssertEqual(0, data.count, "data from empty string is empty")
+    }
 }
 
 // Tests from Swift SDK Overlay
diff --git a/TestFoundation/TestNSDecimal.swift b/TestFoundation/TestNSDecimal.swift
index f28e16c..ffddd40 100644
--- a/TestFoundation/TestNSDecimal.swift
+++ b/TestFoundation/TestNSDecimal.swift
@@ -593,6 +593,8 @@
 
         number = NSDecimalNumber(mantissa:1, exponent:0, isNegative:false)
         XCTAssertTrue(number.boolValue, "Should have received true")
+
+        XCTAssertEqual(100,number.objCType.pointee, "ObjC type for NSDecimalNumber is 'd'")
     }
 
     func test_ZeroPower() {
diff --git a/TestFoundation/TestNSDictionary.swift b/TestFoundation/TestNSDictionary.swift
index 002a119..ff415ef 100644
--- a/TestFoundation/TestNSDictionary.swift
+++ b/TestFoundation/TestNSDictionary.swift
@@ -205,7 +205,7 @@
     }
 
     private func createTestFile(_ path: String, _contents: Data) -> String? {
-        let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().uuidString + "/"
+        let tempDir = NSTemporaryDirectory() + "TestFoundation_Playground_" + NSUUID().uuidString + "/"
         do {
             try FileManager.default.createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
             if FileManager.default.createFile(atPath: tempDir + "/" + path, contents: _contents,
diff --git a/TestFoundation/TestNSFileHandle.swift b/TestFoundation/TestNSFileHandle.swift
index 69a74cc..93357ff 100644
--- a/TestFoundation/TestNSFileHandle.swift
+++ b/TestFoundation/TestNSFileHandle.swift
@@ -19,6 +19,7 @@
     static var allTests : [(String, (TestNSFileHandle) -> () throws -> ())] {
         return [
                    ("test_pipe", test_pipe),
+                   ("test_nullDevice", test_nullDevice),
         ]
     }
 
@@ -38,4 +39,23 @@
             XCTAssertEqual(output, input)
         }
     }
+
+    func test_nullDevice() {
+        let fh = FileHandle.nullDevice
+
+        XCTAssertEqual(fh.fileDescriptor, -1)
+        fh.closeFile()
+        fh.seek(toFileOffset: 10)
+        XCTAssertEqual(fh.offsetInFile, 0)
+        XCTAssertEqual(fh.seekToEndOfFile(), 0)
+        XCTAssertEqual(fh.readData(ofLength: 15).count, 0)
+        fh.synchronizeFile()
+
+        fh.write(Data(bytes: [1,2]))
+        fh.seek(toFileOffset: 0)
+        XCTAssertEqual(fh.availableData.count, 0)
+        fh.write(Data(bytes: [1,2]))
+        fh.seek(toFileOffset: 0)
+        XCTAssertEqual(fh.readDataToEndOfFile().count, 0)
+    }
 }
diff --git a/TestFoundation/TestNSFileManager.swift b/TestFoundation/TestNSFileManager.swift
index b0c9afd..1bdffd3 100644
--- a/TestFoundation/TestNSFileManager.swift
+++ b/TestFoundation/TestNSFileManager.swift
@@ -38,7 +38,7 @@
     
     func test_createDirectory() {
         let fm = FileManager.default
-        let path = "/tmp/testdir\(NSUUID().uuidString)"
+        let path = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)"
         
         ignoreError { try fm.removeItem(atPath: path) }
         
@@ -63,7 +63,7 @@
     
     func test_createFile() {
         let fm = FileManager.default
-        let path = "/tmp/testfile\(NSUUID().uuidString)"
+        let path = NSTemporaryDirectory() + "testfile\(NSUUID().uuidString)"
         
         ignoreError { try fm.removeItem(atPath: path) }
         
@@ -83,8 +83,8 @@
 
     func test_moveFile() {
         let fm = FileManager.default
-        let path = "/tmp/testfile\(NSUUID().uuidString)"
-        let path2 = "/tmp/testfile2\(NSUUID().uuidString)"
+        let path = NSTemporaryDirectory() + "testfile\(NSUUID().uuidString)"
+        let path2 = NSTemporaryDirectory() + "testfile2\(NSUUID().uuidString)"
 
         func cleanup() {
             ignoreError { try fm.removeItem(atPath: path) }
@@ -114,7 +114,7 @@
     
     func test_fileAttributes() {
         let fm = FileManager.default
-        let path = "/tmp/test_fileAttributes\(NSUUID().uuidString)"
+        let path = NSTemporaryDirectory() + "test_fileAttributes\(NSUUID().uuidString)"
 
         ignoreError { try fm.removeItem(atPath: path) }
         
@@ -161,7 +161,7 @@
     }
     
     func test_setFileAttributes() {
-        let path = "/tmp/test_setFileAttributes\(NSUUID().uuidString)"
+        let path = NSTemporaryDirectory() + "test_setFileAttributes\(NSUUID().uuidString)"
         let fm = FileManager.default
         
         ignoreError { try fm.removeItem(atPath: path) }
@@ -189,10 +189,10 @@
     func test_pathEnumerator() {
         let fm = FileManager.default
         let testDirName = "testdir\(NSUUID().uuidString)"
-        let basePath = "/tmp/\(testDirName)"
-        let itemPath = "/tmp/\(testDirName)/item"
-        let basePath2 = "/tmp/\(testDirName)/path2"
-        let itemPath2 = "/tmp/\(testDirName)/path2/item"
+        let basePath = NSTemporaryDirectory() + "\(testDirName)"
+        let itemPath = NSTemporaryDirectory() + "\(testDirName)/item"
+        let basePath2 = NSTemporaryDirectory() + "\(testDirName)/path2"
+        let itemPath2 = NSTemporaryDirectory() + "\(testDirName)/path2/item"
         
         ignoreError { try fm.removeItem(atPath: basePath) }
         
@@ -222,8 +222,8 @@
     func test_directoryEnumerator() {
         let fm = FileManager.default
         let testDirName = "testdir\(NSUUID().uuidString)"
-        let path = "/tmp/\(testDirName)"
-        let itemPath = "/tmp/\(testDirName)/item"
+        let path = NSTemporaryDirectory() + "\(testDirName)"
+        let itemPath = NSTemporaryDirectory() + "\(testDirName)/item"
         
         ignoreError { try fm.removeItem(atPath: path) }
         
@@ -244,8 +244,8 @@
             XCTFail()
         }
         
-        let subDirPath = "/tmp/\(testDirName)/testdir2"
-        let subDirItemPath = "/tmp/\(testDirName)/testdir2/item"
+        let subDirPath = NSTemporaryDirectory() + "\(testDirName)/testdir2"
+        let subDirItemPath = NSTemporaryDirectory() + "\(testDirName)/testdir2/item"
         do {
             try fm.createDirectory(atPath: subDirPath, withIntermediateDirectories: false, attributes: nil)
             let _ = fm.createFile(atPath: subDirItemPath, contents: Data(), attributes: nil)
@@ -320,9 +320,9 @@
     func test_contentsOfDirectoryAtPath() {
         let fm = FileManager.default
         let testDirName = "testdir\(NSUUID().uuidString)"
-        let path = "/tmp/\(testDirName)"
-        let itemPath1 = "/tmp/\(testDirName)/item"
-        let itemPath2 = "/tmp/\(testDirName)/item2"
+        let path = NSTemporaryDirectory() + "\(testDirName)"
+        let itemPath1 = NSTemporaryDirectory() + "\(testDirName)/item"
+        let itemPath2 = NSTemporaryDirectory() + "\(testDirName)/item2"
         
         ignoreError { try fm.removeItem(atPath: path) }
         
@@ -363,11 +363,11 @@
     
     func test_subpathsOfDirectoryAtPath() {
         let fm = FileManager.default
-        let path = "/tmp/testdir"
-        let path2 = "/tmp/testdir/sub"
-        let itemPath1 = "/tmp/testdir/item"
-        let itemPath2 = "/tmp/testdir/item2"
-        let itemPath3 = "/tmp/testdir/sub/item3"
+        let path = NSTemporaryDirectory() + "testdir"
+        let path2 = NSTemporaryDirectory() + "testdir/sub"
+        let itemPath1 = NSTemporaryDirectory() + "testdir/item"
+        let itemPath2 = NSTemporaryDirectory() + "testdir/item2"
+        let itemPath3 = NSTemporaryDirectory() + "testdir/sub/item3"
                 
         ignoreError { try fm.removeItem(atPath: path) }
         
diff --git a/TestFoundation/TestNSJSONSerialization.swift b/TestFoundation/TestNSJSONSerialization.swift
index d40a1c0..3ce12e8 100644
--- a/TestFoundation/TestNSJSONSerialization.swift
+++ b/TestFoundation/TestNSJSONSerialization.swift
@@ -777,7 +777,7 @@
         
         // Cannot generate "true"/"false" currently
         json = [NSNumber(value:false),NSNumber(value:true)]
-        XCTAssertEqual(try trySerialize(json), "[0,1]")
+        XCTAssertEqual(try trySerialize(json), "[false,true]")
     }
     
     func test_serialize_stringEscaping() {
@@ -931,16 +931,18 @@
     
     func test_booleanJSONObject() {
         do {
-            let mydata = try JSONSerialization.data(withJSONObject: [true])
-            XCTAssertEqual(String(data: mydata, encoding: String.Encoding.utf8), "[1]")
+            let objectLikeBoolArray = try JSONSerialization.data(withJSONObject: [true, NSNumber(value: false), NSNumber(value: true)] as Array<Any>)
+            XCTAssertEqual(String(data: objectLikeBoolArray, encoding: .utf8), "[true,false,true]")
+            let valueLikeBoolArray = try JSONSerialization.data(withJSONObject: [false, true, false])
+            XCTAssertEqual(String(data: valueLikeBoolArray, encoding: .utf8), "[false,true,false]")
         } catch {
             XCTFail("Failed during serialization")
         }
-        XCTAssertTrue(JSONSerialization.isValidJSONObject([1]))
+        XCTAssertTrue(JSONSerialization.isValidJSONObject([true]))
     }
 
     private func createTestFile(_ path: String,_contents: Data) -> String? {
-        let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().uuidString + "/"
+        let tempDir = NSTemporaryDirectory() + "TestFoundation_Playground_" + NSUUID().uuidString + "/"
         do {
             try FileManager.default.createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
             if FileManager.default.createFile(atPath: tempDir + "/" + path, contents: _contents,
diff --git a/TestFoundation/TestNSLocale.swift b/TestFoundation/TestNSLocale.swift
index 3d18791..f83edf3 100644
--- a/TestFoundation/TestNSLocale.swift
+++ b/TestFoundation/TestNSLocale.swift
@@ -19,9 +19,24 @@
     static var allTests: [(String, (TestNSLocale) -> () throws -> Void)] {
         return [
             ("test_constants", test_constants),
+            ("test_Identifier", test_Identifier),
             ("test_copy", test_copy)
         ]
     }
+
+    func test_Identifier() {
+        // Current locale identifier should not be empty
+        // Or things like NSNumberFormatter spellOut style won't work
+        XCTAssertFalse(Locale.current.identifier.isEmpty)
+
+        let enUSID = "en_US"
+        let locale = Locale(identifier: enUSID)
+        XCTAssertEqual(enUSID, locale.identifier)
+
+        let deDEID = "de_DE"
+        let germanLocale = Locale(identifier: deDEID)
+        XCTAssertEqual(deDEID, germanLocale.identifier)
+    }
     
     func test_constants() {
         XCTAssertEqual(NSCurrentLocaleDidChangeNotification, "kCFLocaleCurrentLocaleDidChangeNotification",
diff --git a/TestFoundation/TestNSNotificationCenter.swift b/TestFoundation/TestNSNotificationCenter.swift
old mode 100755
new mode 100644
diff --git a/TestFoundation/TestNSNumberFormatter.swift b/TestFoundation/TestNSNumberFormatter.swift
index 9511770..222b3d2 100644
--- a/TestFoundation/TestNSNumberFormatter.swift
+++ b/TestFoundation/TestNSNumberFormatter.swift
@@ -53,7 +53,9 @@
             ("test_lenient", test_lenient),
             ("test_minimumSignificantDigits", test_minimumSignificantDigits),
             ("test_maximumSignificantDigits", test_maximumSignificantDigits),
-            ("test_stringFor", test_stringFor)
+            ("test_stringFor", test_stringFor),
+            ("test_numberFrom", test_numberFrom),
+            //("test_en_US_initialValues", test_en_US_initialValues)
         ]
     }
     
@@ -68,11 +70,15 @@
         XCTAssertEqual(formattedString, "T 42_00")
          */
     }
-    
+
     func test_decimalSeparator() {
         let numberFormatter = NumberFormatter()
         numberFormatter.numberStyle = .decimal
-        numberFormatter.decimalSeparator = "-"
+
+        let separator = "-"
+        numberFormatter.decimalSeparator = separator
+        XCTAssertEqual(numberFormatter.decimalSeparator, separator)
+
         let formattedString = numberFormatter.string(from: 42.42)
         XCTAssertEqual(formattedString, "42-42")
     }
@@ -147,14 +153,28 @@
     }
     
     func test_plusSignSymbol() {
-        //FIXME: How do we show the plus sign from a NSNumberFormatter?
+        // ex. 1.0E+1 in scientific notation
+        let numberFormatter = NumberFormatter()
+        let format = "#E+0"
+        numberFormatter.format = format
+        XCTAssertEqual(numberFormatter.format, format)
 
-//        let numberFormatter = NumberFormatter()
-//        numberFormatter.plusSign = "πŸ‘"
-//        let formattedString = numberFormatter.stringFromNumber(42)
-//        XCTAssertEqual(formattedString, "πŸ‘42")
+        let sign = "πŸ‘"
+        numberFormatter.plusSign = sign
+        XCTAssertEqual(numberFormatter.plusSign, sign)
+
+        let formattedString = numberFormatter.string(from: 420000000000000000)
+        XCTAssertNotNil(formattedString)
+        XCTAssertEqual(formattedString, "4.2EπŸ‘17")
+
+        // Verify a negative exponent does not have the πŸ‘
+        let noPlusString = numberFormatter.string(from: -0.420)
+        XCTAssertNotNil(noPlusString)
+        if let fmt = noPlusString {
+            XCTAssertFalse(fmt.contains(sign), "Expected format of -0.420 (-4.2E-1) shouldn't have a plus sign which was set as \(sign)")
+        }
     }
-    
+
     func test_currencySymbol() {
         // Disabled due to [SR-250]
         /*
@@ -316,14 +336,30 @@
         */
     }
 
-    //FIXME: Something is wrong with numberFromString implementation, I don't know exactly why, but it's not working.
     func test_lenient() {
-//        let numberFormatter = NumberFormatter()
-//        numberFormatter.numberStyle = .CurrencyStyle
-//        let nilNumberBeforeLenient = numberFormatter.numberFromString("42")
+        let numberFormatter = NumberFormatter()
+        // Not lenient by default
+        XCTAssertFalse(numberFormatter.isLenient)
+
+        // Lenient allows wrong style -- not lenient here
+        numberFormatter.numberStyle = .spellOut
+        XCTAssertEqual(numberFormatter.numberStyle, .spellOut)
+//        let nilNumber = numberFormatter.number(from: "2.22")
+        // FIXME: Not nil on Linux?
+        //XCTAssertNil(nilNumber)
+        // Lenient allows wrong style
+        numberFormatter.isLenient = true
+        XCTAssertTrue(numberFormatter.isLenient)
+        let number = numberFormatter.number(from: "2.22")
+        XCTAssertEqual(number, 2.22)
+
+        // TODO: Add some tests with currency after [SR-250] resolved
+//        numberFormatter.numberStyle = .currency
+//        let nilNumberBeforeLenient = numberFormatter.number(from: "42")
+//
 //        XCTAssertNil(nilNumberBeforeLenient)
-//        numberFormatter.lenient = true
-//        let numberAfterLenient = numberFormatter.numberFromString("42.42")
+//        numberFormatter.isLenient = true
+//        let numberAfterLenient = numberFormatter.number(from: "42.42")
 //        XCTAssertEqual(numberAfterLenient, 42.42)
     }
     
@@ -353,7 +389,76 @@
         XCTAssertEqual(numberFormatter.string(for: NSNumber(value: 99.1))!, "99")
         XCTAssertNil(numberFormatter.string(for: "NaN"))
         XCTAssertNil(numberFormatter.string(for: NSString(string: "NaN")))
+
+        numberFormatter.numberStyle = .spellOut
+        XCTAssertEqual(numberFormatter.string(for: 234), "two hundred thirty-four")
+        XCTAssertEqual(numberFormatter.string(for: 2007), "two thousand seven")
+        XCTAssertEqual(numberFormatter.string(for: 3), "three")
+        XCTAssertEqual(numberFormatter.string(for: 0.3), "zero point three")
+
+        numberFormatter.locale = Locale(identifier: "zh_CN")
+        numberFormatter.numberStyle = .spellOut
+        XCTAssertEqual(numberFormatter.string(from: 11.4), "十一点四")
+
+        numberFormatter.locale = Locale(identifier: "fr_FR")
+        numberFormatter.numberStyle = .spellOut
+        XCTAssertEqual(numberFormatter.string(from: 11.4), "onze virgule quatre")
+
     }
-  
+
+    func test_numberFrom() {
+        let numberFormatter = NumberFormatter()
+        XCTAssertEqual(numberFormatter.number(from: "10"), 10)
+        XCTAssertEqual(numberFormatter.number(from: "3.14"), 3.14)
+        XCTAssertEqual(numberFormatter.number(from: "0.01"), 0.01)
+        XCTAssertEqual(numberFormatter.number(from: ".01"), 0.01)
+
+        // These don't work unless lenient/style set
+        numberFormatter.numberStyle = .decimal
+        XCTAssertEqual(numberFormatter.number(from: "1,001"), 1001)
+        XCTAssertEqual(numberFormatter.number(from: "1,050,001"), 1050001)
+
+        numberFormatter.numberStyle = .spellOut
+        XCTAssertEqual(numberFormatter.number(from: "two thousand and seven"), 2007)
+        XCTAssertEqual(numberFormatter.number(from: "one point zero"), 1.0)
+        XCTAssertEqual(numberFormatter.number(from: "one hundred million"), 1E8)
+
+        numberFormatter.locale = Locale(identifier: "zh_CN")
+        numberFormatter.numberStyle = .spellOut
+        XCTAssertEqual(numberFormatter.number(from: "十一点四"), 11.4)
+
+        numberFormatter.locale = Locale(identifier: "fr_FR")
+        numberFormatter.numberStyle = .spellOut
+        XCTAssertEqual(numberFormatter.number(from: "onze virgule quatre"), 11.4)
+    }
+
+    func test_en_US_initialValues() {
+        // Symbols should be extractable
+        // At one point, none of this passed!
+
+        let numberFormatter = NumberFormatter();
+        numberFormatter.locale = Locale(identifier: "en_US")
+
+        // TODO: Check if this is true for all versions...
+        XCTAssertEqual(numberFormatter.format, "#;0;#")
+
+        XCTAssertEqual(numberFormatter.plusSign, "+")
+        XCTAssertEqual(numberFormatter.minusSign, "-")
+        XCTAssertEqual(numberFormatter.decimalSeparator, ".")
+        XCTAssertEqual(numberFormatter.groupingSeparator, ",")
+        XCTAssertEqual(numberFormatter.nilSymbol, "")
+        XCTAssertEqual(numberFormatter.notANumberSymbol, "NaN")
+        XCTAssertEqual(numberFormatter.positiveInfinitySymbol, "+∞")
+        XCTAssertEqual(numberFormatter.negativeInfinitySymbol, "-∞")
+        XCTAssertEqual(numberFormatter.positivePrefix, "")
+        XCTAssertEqual(numberFormatter.negativePrefix, "-")
+        XCTAssertEqual(numberFormatter.positiveSuffix, "")
+        XCTAssertEqual(numberFormatter.negativeSuffix, "")
+        XCTAssertEqual(numberFormatter.percentSymbol, "%")
+        XCTAssertEqual(numberFormatter.perMillSymbol, "‰")
+        XCTAssertEqual(numberFormatter.exponentSymbol, "E")
+        XCTAssertEqual(numberFormatter.groupingSeparator, ",")
+        XCTAssertEqual(numberFormatter.paddingCharacter, "*")
+    }
 }
 
diff --git a/TestFoundation/TestNSPredicate.swift b/TestFoundation/TestNSPredicate.swift
index 4275d9a..641d605 100644
--- a/TestFoundation/TestNSPredicate.swift
+++ b/TestFoundation/TestNSPredicate.swift
@@ -27,6 +27,8 @@
             ("test_filterNSMutableSet", test_filterNSMutableSet),
             ("test_filterNSOrderedSet", test_filterNSOrderedSet),
             ("test_filterNSMutableOrderedSet", test_filterNSMutableOrderedSet),
+            ("test_NSCoding", test_NSCoding),
+            ("test_copy", test_copy),
         ]
     }
 
@@ -94,4 +96,15 @@
         expectedOrderedSet.addObjects(from: expectedArray)
         XCTAssertEqual(expectedOrderedSet, orderedSet)
     }
+    
+    func test_NSCoding() {
+        let predicateA = NSPredicate(value: true)
+        let predicateB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: predicateA)) as! NSPredicate
+        XCTAssertEqual(predicateA, predicateB, "Archived then unarchived uuid must be equal.")
+    }
+    
+    func test_copy() {
+        let predicate = NSPredicate(value: true)
+        XCTAssert(predicate.isEqual(predicate.copy()))
+    }
 }
diff --git a/TestFoundation/TestNSRange.swift b/TestFoundation/TestNSRange.swift
index 927e989..75a6471 100644
--- a/TestFoundation/TestNSRange.swift
+++ b/TestFoundation/TestNSRange.swift
@@ -21,8 +21,7 @@
     
     static var allTests: [(String, (TestNSRange) -> () throws -> Void)] {
         return [
-            // currently disabled due to pending requirements for NSString
-            // ("test_NSRangeFromString", test_NSRangeFromString ),
+            ("test_NSRangeFromString", test_NSRangeFromString ),
             ("test_NSRangeBridging", test_NSRangeBridging),
             ("test_NSMaxRange", test_NSMaxRange),
             ("test_NSLocationInRange", test_NSLocationInRange),
diff --git a/TestFoundation/TestNSRunLoop.swift b/TestFoundation/TestNSRunLoop.swift
old mode 100755
new mode 100644
diff --git a/TestFoundation/TestNSStream.swift b/TestFoundation/TestNSStream.swift
index f2daf43..8bb4c5c 100644
--- a/TestFoundation/TestNSStream.swift
+++ b/TestFoundation/TestNSStream.swift
@@ -118,7 +118,7 @@
     }
     
     func test_InputStreamInvalidPath() {
-        let fileStream: InputStream = InputStream(fileAtPath: "/tmp/file.txt")!
+        let fileStream: InputStream = InputStream(fileAtPath: NSTemporaryDirectory() + "file.txt")!
         XCTAssertEqual(Stream.Status.notOpen, fileStream.streamStatus)
         fileStream.open()
         XCTAssertEqual(Stream.Status.error, fileStream.streamStatus)
@@ -217,7 +217,7 @@
     }
     
     private func createTestFile(_ path: String, _contents: Data) -> String? {
-        let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().uuidString + "/"
+        let tempDir = NSTemporaryDirectory() + "TestFoundation_Playground_" + NSUUID().uuidString + "/"
         do {
             try FileManager.default.createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
             if FileManager.default.createFile(atPath: tempDir + "/" + path, contents: _contents,
diff --git a/TestFoundation/TestNSString.swift b/TestFoundation/TestNSString.swift
index 1767982..362e075 100644
--- a/TestFoundation/TestNSString.swift
+++ b/TestFoundation/TestNSString.swift
@@ -81,7 +81,11 @@
             ("test_resolvingSymlinksInPath", test_resolvingSymlinksInPath),
             ("test_expandingTildeInPath", test_expandingTildeInPath),
             ("test_standardizingPath", test_standardizingPath),
-            ("test_removingPercentEncoding", test_removingPercentEncoding),
+            ("test_addingPercentEncoding", test_addingPercentEncoding),
+            ("test_removingPercentEncodingInLatin", test_removingPercentEncodingInLatin),
+            ("test_removingPercentEncodingInNonLatin", test_removingPercentEncodingInNonLatin),
+            ("test_removingPersentEncodingWithoutEncoding", test_removingPersentEncodingWithoutEncoding),
+            ("test_addingPercentEncodingAndBack", test_addingPercentEncodingAndBack),
             ("test_stringByAppendingPathExtension", test_stringByAppendingPathExtension),
             ("test_deletingPathExtension", test_deletingPathExtension),
             ("test_ExternalRepresentation", test_ExternalRepresentation),
@@ -415,11 +419,11 @@
     
     func test_completePathIntoString() {
         let fileNames = [
-            "/tmp/Test_completePathIntoString_01",
-            "/tmp/test_completePathIntoString_02",
-            "/tmp/test_completePathIntoString_01.txt",
-            "/tmp/test_completePathIntoString_01.dat",
-            "/tmp/test_completePathIntoString_03.DAT"
+            NSTemporaryDirectory() + "Test_completePathIntoString_01",
+            NSTemporaryDirectory() + "test_completePathIntoString_02",
+            NSTemporaryDirectory() + "test_completePathIntoString_01.txt",
+            NSTemporaryDirectory() + "test_completePathIntoString_01.dat",
+            NSTemporaryDirectory() + "test_completePathIntoString_03.DAT"
         ]
         
         guard ensureFiles(fileNames) else {
@@ -428,7 +432,7 @@
         }
 
         let tmpPath = { (path: String) -> String in
-            return "/tmp/\(path)"
+            return NSTemporaryDirectory() + "\(path)"
         }
 
         do {
@@ -459,9 +463,9 @@
         }
         
         let fileNames2 = [
-            "/tmp/ABC/",
-            "/tmp/ABCD/",
-            "/tmp/abcde"
+            NSTemporaryDirectory() + "ABC/",
+            NSTemporaryDirectory() + "ABCD/",
+            NSTemporaryDirectory() + "abcde"
         ]
         
         guard ensureFiles(fileNames2) else {
@@ -567,7 +571,7 @@
         
         // Next check has no sense on Linux due to case sensitive file system.
         #if os(OSX)
-        guard ensureFiles(["/tmp/ABC/temp.txt"]) else {
+        guard ensureFiles([NSTemporaryDirectory() + "ABC/temp.txt"]) else {
             XCTAssert(false, "Could not create temp files for testing.")
             return
         }
@@ -602,6 +606,9 @@
         let characterSet = CharacterSet.whitespaces
         let string: NSString = " abc   "
         XCTAssertEqual(string.trimmingCharacters(in: characterSet), "abc")
+        
+        let emojiString: NSString = " \u{1F62C}  "
+        XCTAssertEqual(emojiString.trimmingCharacters(in: characterSet), "\u{1F62C}")
     }
     
     func test_initializeWithFormat() {
@@ -864,13 +871,66 @@
         }
     }
 
-    func test_removingPercentEncoding() {
+    func test_addingPercentEncoding() {
+        let s1 = "a b".addingPercentEncoding(withAllowedCharacters: .alphanumerics)
+        XCTAssertEqual(s1, "a%20b")
+        
+        let s2 = "\u{0434}\u{043E}\u{043C}".addingPercentEncoding(withAllowedCharacters: .alphanumerics)
+        XCTAssertEqual(s2, "%D0%B4%D0%BE%D0%BC")
+    }
+    
+    func test_removingPercentEncodingInLatin() {
         let s1 = "a%20b".removingPercentEncoding
         XCTAssertEqual(s1, "a b")
         let s2 = "a%1 b".removingPercentEncoding
         XCTAssertNil(s2, "returns nil for a string with an invalid percent encoding")
     }
     
+    func test_removingPercentEncodingInNonLatin() {
+        let s1 = "\u{043C}\u{043E}\u{0439}%20\u{0434}\u{043E}\u{043C}".removingPercentEncoding
+        XCTAssertEqual(s1, "\u{043C}\u{043E}\u{0439} \u{0434}\u{043E}\u{043C}")
+        
+        let s2 = "%D0%B4%D0%BE%D0%BC".removingPercentEncoding
+        XCTAssertEqual(s2, "\u{0434}\u{043E}\u{043C}")
+        
+        let s3 = "\u{00E0}a%1 b".removingPercentEncoding
+        XCTAssertNil(s3, "returns nil for a string with an invalid percent encoding")
+    }
+    
+    func test_removingPersentEncodingWithoutEncoding() {
+        let cyrillicString = "\u{0434}\u{043E}\u{043C}"
+        let cyrillicEscapedString = cyrillicString.removingPercentEncoding
+        XCTAssertEqual(cyrillicString, cyrillicEscapedString)
+        
+        let chineseString = "\u{623F}\u{5B50}"
+        let chineseEscapedString = chineseString.removingPercentEncoding
+        XCTAssertEqual(chineseString, chineseEscapedString)
+        
+        let arabicString = "\u{0645}\u{0646}\u{0632}\u{0644}"
+        let arabicEscapedString = arabicString.removingPercentEncoding
+        XCTAssertEqual(arabicString, arabicEscapedString)
+        
+        let randomString = "\u{00E0}\u{00E6}"
+        let randomEscapedString = randomString.removingPercentEncoding
+        XCTAssertEqual(randomString, randomEscapedString)
+        
+        let latinString = "home"
+        let latinEscapedString = latinString.removingPercentEncoding
+        XCTAssertEqual(latinString, latinEscapedString)
+    }
+    
+    func test_addingPercentEncodingAndBack() {
+        let latingString = "a b"
+        let escapedLatingString = latingString.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
+        let returnedLatingString = escapedLatingString?.removingPercentEncoding
+        XCTAssertEqual(returnedLatingString, latingString)
+        
+        let cyrillicString = "\u{0434}\u{043E}\u{043C}"
+        let escapedCyrillicString = cyrillicString.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
+        let returnedCyrillicString = escapedCyrillicString?.removingPercentEncoding
+        XCTAssertEqual(returnedCyrillicString, cyrillicString)
+    }
+    
     func test_stringByAppendingPathExtension() {
         let values = [
             NSString(string: "/tmp/scratch.old") : "/tmp/scratch.old.tiff",
diff --git a/TestFoundation/TestNSTimer.swift b/TestFoundation/TestNSTimer.swift
old mode 100755
new mode 100644
diff --git a/TestFoundation/TestNSURL.swift b/TestFoundation/TestNSURL.swift
index 87409b5..b174390 100644
--- a/TestFoundation/TestNSURL.swift
+++ b/TestFoundation/TestNSURL.swift
@@ -352,7 +352,7 @@
     
     func test_URLByResolvingSymlinksInPath() {
         let files = [
-            "/tmp/ABC/test_URLByResolvingSymlinksInPath"
+            NSTemporaryDirectory() + "ABC/test_URLByResolvingSymlinksInPath"
         ]
         
         guard ensureFiles(files) else {
diff --git a/TestFoundation/TestNSURLCredential.swift b/TestFoundation/TestNSURLCredential.swift
index 542c857..037b114 100644
--- a/TestFoundation/TestNSURLCredential.swift
+++ b/TestFoundation/TestNSURLCredential.swift
@@ -21,7 +21,8 @@
     static var allTests: [(String, (TestNSURLCredential) -> () throws -> Void)] {
         return [
                    ("test_construction", test_construction),
-                   ("test_copy", test_copy)
+                   ("test_copy", test_copy),
+                   ("test_NSCoding", test_NSCoding)
         ]
     }
     
@@ -39,4 +40,10 @@
         let copy = credential.copy() as! URLCredential
         XCTAssertTrue(copy.isEqual(credential))
     }
+    
+    func test_NSCoding() {
+        let credentialA = URLCredential(user: "swiftUser", password: "swiftPassword", persistence: .forSession)
+        let credentialB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: credentialA)) as! URLCredential
+        XCTAssertEqual(credentialA, credentialB, "Archived then unarchived url credential must be equal.")
+    }
 }
diff --git a/TestFoundation/TestNSURLRequest.swift b/TestFoundation/TestNSURLRequest.swift
index 5dde4ef..b9b0353 100644
--- a/TestFoundation/TestNSURLRequest.swift
+++ b/TestFoundation/TestNSURLRequest.swift
@@ -27,6 +27,9 @@
             ("test_mutableCopy_1", test_mutableCopy_1),
             ("test_mutableCopy_2", test_mutableCopy_2),
             ("test_mutableCopy_3", test_mutableCopy_3),
+            ("test_NSCoding_1", test_NSCoding_1),
+            ("test_NSCoding_2", test_NSCoding_2),
+            ("test_NSCoding_3", test_NSCoding_3)
         ]
     }
     
@@ -203,4 +206,38 @@
         XCTAssertEqual(originalRequest.url, urlA)
         XCTAssertNil(originalRequest.allHTTPHeaderFields)
     }
+    
+    func test_NSCoding_1() {
+        let url = URL(string: "https://apple.com")!
+        let requestA = NSURLRequest(url: url)
+        let requestB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: requestA)) as! NSURLRequest
+        XCTAssertEqual(requestA, requestB, "Archived then unarchived url request must be equal.")
+    }
+    
+    func test_NSCoding_2() {
+        let url = URL(string: "https://apple.com")!
+        let requestA = NSMutableURLRequest(url: url)
+        //Also checks crash on NSData.bytes
+        requestA.httpBody = Data()
+        let requestB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: requestA)) as! NSURLRequest
+        XCTAssertEqual(requestA, requestB, "Archived then unarchived url request must be equal.")
+        //Check `.httpBody` as it is not checked in `isEqual(_:)`
+        XCTAssertEqual(requestB.httpBody, requestA.httpBody)
+    }
+    
+    func test_NSCoding_3() {
+        let url = URL(string: "https://apple.com")!
+        let urlForDocument = URL(string: "http://ibm.com")!
+        
+        let requestA = NSMutableURLRequest(url: url)
+        requestA.mainDocumentURL = urlForDocument
+        //Also checks crash on NSData.bytes
+        requestA.httpBody = Data(bytes: [1, 2, 3])
+        let requestB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: requestA)) as! NSURLRequest
+        XCTAssertEqual(requestA, requestB, "Archived then unarchived url request must be equal.")
+        //Check `.httpBody` as it is not checked in `isEqual(_:)`
+        XCTAssertNotNil(requestB.httpBody)
+        XCTAssertEqual(3, requestB.httpBody!.count)
+        XCTAssertEqual(requestB.httpBody, requestA.httpBody)
+    }
 }
diff --git a/TestFoundation/TestNSURLResponse.swift b/TestFoundation/TestNSURLResponse.swift
index 9e67ffa..dfece22 100644
--- a/TestFoundation/TestNSURLResponse.swift
+++ b/TestFoundation/TestNSURLResponse.swift
@@ -29,6 +29,7 @@
             ("test_suggestedFilename_2", test_suggestedFilename_2),
             ("test_suggestedFilename_3", test_suggestedFilename_3),
             ("test_copywithzone", test_copyWithZone),
+            ("test_NSCoding", test_NSCoding),
         ]
     }
     
@@ -91,6 +92,19 @@
         let res = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil)
         XCTAssertTrue(res.isEqual(res.copy() as! NSObject))
     }
+    
+    func test_NSCoding() {
+        let url = URL(string: "https://apple.com")!
+        let responseA = URLResponse(url: url, mimeType: "txt", expectedContentLength: 0, textEncodingName: nil)
+        let responseB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: responseA)) as! URLResponse
+        
+        //On macOS unarchived Archived then unarchived `URLResponse` is not equal.
+        XCTAssertEqual(responseA.url, responseB.url, "Archived then unarchived url response must be equal.")
+        XCTAssertEqual(responseA.mimeType, responseB.mimeType, "Archived then unarchived url response must be equal.")
+        XCTAssertEqual(responseA.expectedContentLength, responseB.expectedContentLength, "Archived then unarchived url response must be equal.")
+        XCTAssertEqual(responseA.textEncodingName, responseB.textEncodingName, "Archived then unarchived url response must be equal.")
+        XCTAssertEqual(responseA.suggestedFilename, responseB.suggestedFilename, "Archived then unarchived url response must be equal.")
+    }
 }
 
 
@@ -127,6 +141,8 @@
                    ("test_MIMETypeAndCharacterEncoding_1", test_MIMETypeAndCharacterEncoding_1),
                    ("test_MIMETypeAndCharacterEncoding_2", test_MIMETypeAndCharacterEncoding_2),
                    ("test_MIMETypeAndCharacterEncoding_3", test_MIMETypeAndCharacterEncoding_3),
+                   
+                   ("test_NSCoding", test_NSCoding),
         ]
     }
     
@@ -292,4 +308,28 @@
         XCTAssertEqual(sut?.mimeType, "text/html")
         XCTAssertEqual(sut?.textEncodingName, "iso-8859-4")
     }
+    
+    // NSCoding
+    
+    func test_NSCoding() {
+        let url = URL(string: "https://apple.com")!
+        let f = ["Content-Type": "text/HTML; charset=ISO-8859-4"]
+        
+        let responseA = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: f)!
+        let responseB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: responseA)) as! HTTPURLResponse
+        
+        //On macOS unarchived Archived then unarchived `URLResponse` is not equal.
+        XCTAssertEqual(responseA.statusCode, responseB.statusCode, "Archived then unarchived http url response must be equal.")
+        XCTAssertEqual(Array(responseA.allHeaderFields.keys), Array(responseB.allHeaderFields.keys), "Archived then unarchived http url response must be equal.")
+        
+        for key in responseA.allHeaderFields.keys {
+            XCTAssertEqual(responseA.allHeaderFields[key] as? String, responseB.allHeaderFields[key] as? String, "Archived then unarchived http url response must be equal.")
+        }
+        
+        XCTAssertEqual(responseA.url, responseB.url, "Archived then unarchived http url response must be equal.")
+        XCTAssertEqual(responseA.mimeType, responseB.mimeType, "Archived then unarchived http url response must be equal.")
+        XCTAssertEqual(responseA.expectedContentLength, responseB.expectedContentLength, "Archived then unarchived http url response must be equal.")
+        XCTAssertEqual(responseA.textEncodingName, responseB.textEncodingName, "Archived then unarchived http url response must be equal.")
+        XCTAssertEqual(responseA.suggestedFilename, responseB.suggestedFilename, "Archived then unarchived http url response must be equal.")
+    }
 }
diff --git a/TestFoundation/TestNotification.swift b/TestFoundation/TestNotification.swift
new file mode 100644
index 0000000..9c1bd38
--- /dev/null
+++ b/TestFoundation/TestNotification.swift
@@ -0,0 +1,56 @@
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2016 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
+//
+
+
+
+#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
+    import Foundation
+    import XCTest
+#else
+    import SwiftFoundation
+    import SwiftXCTest
+#endif
+
+
+
+class TestNotification : XCTestCase {
+
+    static var allTests: [(String, (TestNotification) -> () throws -> Void)] {
+        return [
+            ("test_customReflection", test_customReflection),
+        ]
+    }
+
+    func test_customReflection() {
+        let someName = "somenotifname"
+        let targetObject = NSObject()
+        let userInfo = ["hello": "world", "indexThis": 350] as [AnyHashable: Any]
+        let notif = Notification(name: Notification.Name(rawValue: someName), object: targetObject, userInfo: userInfo)
+        let mirror = notif.customMirror
+
+        XCTAssertEqual(mirror.displayStyle, .class)
+        XCTAssertNil(mirror.superclassMirror)
+
+        var children = Array(mirror.children).makeIterator()
+        let firstChild = children.next()
+        let secondChild = children.next()
+        let thirdChild = children.next()
+        XCTAssertEqual(firstChild?.label, "name")
+        XCTAssertEqual(firstChild?.value as? String, someName)
+
+        XCTAssertEqual(secondChild?.label, "object")
+        XCTAssertEqual(secondChild?.value as? NSObject, targetObject)
+
+        XCTAssertEqual(thirdChild?.label, "userInfo")
+        XCTAssertEqual((thirdChild?.value as? [AnyHashable: Any])?["hello"] as? String, "world")
+        XCTAssertEqual((thirdChild?.value as? [AnyHashable: Any])?["indexThis"] as? Int, 350)
+
+    }
+
+}
diff --git a/TestFoundation/main.swift b/TestFoundation/main.swift
index 517d740..732bf17 100644
--- a/TestFoundation/main.swift
+++ b/TestFoundation/main.swift
@@ -87,4 +87,5 @@
     testCase(TestProgressFraction.allTests),
     testCase(TestProgress.allTests),
     testCase(TestObjCRuntime.allTests),
+    testCase(TestNotification.allTests),
 ])