Merge pull request #870 from naithar/nscoding-regularexpression

diff --git a/CoreFoundation/Locale.subproj/CFCalendar.c b/CoreFoundation/Locale.subproj/CFCalendar.c
index 392318a..1c18bc7 100644
--- a/CoreFoundation/Locale.subproj/CFCalendar.c
+++ b/CoreFoundation/Locale.subproj/CFCalendar.c
@@ -272,6 +272,7 @@
 	else if (CFEqual(kCFIslamicCalendar, identifier)) identifier = kCFIslamicCalendar;
 	else if (CFEqual(kCFIslamicCivilCalendar, identifier)) identifier = kCFIslamicCivilCalendar;
 	else if (CFEqual(kCFHebrewCalendar, identifier)) identifier = kCFHebrewCalendar;
+       else if (CFEqual(kCFISO8601Calendar, identifier)) identifier = kCFISO8601Calendar;
 //	else if (CFEqual(kCFChineseCalendar, identifier)) identifier = kCFChineseCalendar;
 	else return NULL;
     }
diff --git a/Docs/Status.md b/Docs/Status.md
index 456dff9..d201633 100644
--- a/Docs/Status.md
+++ b/Docs/Status.md
@@ -198,7 +198,7 @@
     |-----------------------------|-----------------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|
     | `NSRegularExpression`       | Complete        | Substantial   |                                                                                                                                 |
     | `Scanner`                   | Mostly Complete | Incomplete    | `scanHex<T: _FloatLike>(_:locale:locationToScanFrom:to:)` and `localizedScannerWithString(_:)` remain unimplemented                                              |
-    | `TextCheckingResult`        | Mostly Complete | Incomplete    | `NSCoding`, `NSCopying`, `resultType`, and `range(at:)` remain unimplemented                                                                                     |
+    | `NSTextCheckingResult`      | Mostly Complete | Incomplete    | `NSCoding`, `NSCopying`, `resultType`, and `range(at:)` remain unimplemented                                                                                     |
     | `NSAttributedString`        | Incomplete      | Incomplete    | `NSCoding`, `NS[Mutable]Copying`, `attributedSubstring(from:)`, `isEqual(to:)`, `init(NSAttributedString:)` remain unimplemented |
     | `NSMutableAttributedString` | Unimplemented   | Incomplete    | Only `addAttribute(_:value:range:)` is implemented                                                                                                               |
     | `NSCharacterSet`            | Mostly Complete | Incomplete    | `NSCoding` remains unimplemented                                                                                                                                 |
diff --git a/Foundation.xcodeproj/project.pbxproj b/Foundation.xcodeproj/project.pbxproj
index a1ace0d..32e5313 100644
--- a/Foundation.xcodeproj/project.pbxproj
+++ b/Foundation.xcodeproj/project.pbxproj
@@ -312,6 +312,7 @@
 		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, ); }; };
 		BD8042161E09857800487EB8 /* TestNSLengthFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD8042151E09857800487EB8 /* TestNSLengthFormatter.swift */; };
+		BDBB65901E256BFA001A7286 /* TestNSEnergyFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = BDBB658F1E256BFA001A7286 /* TestNSEnergyFormatter.swift */; };
 		BDFDF0A71DFF5B3E00C04CC5 /* TestNSPersonNameComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = BDFDF0A61DFF5B3E00C04CC5 /* TestNSPersonNameComponents.swift */; };
 		BF8E65311DC3B3CB005AB5C3 /* TestNotification.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF8E65301DC3B3CB005AB5C3 /* TestNotification.swift */; };
 		CC5249C01D341D23007CB54D /* TestUnitConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC5249BF1D341D23007CB54D /* TestUnitConverter.swift */; };
@@ -755,6 +756,7 @@
 		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>"; };
 		BD8042151E09857800487EB8 /* TestNSLengthFormatter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSLengthFormatter.swift; sourceTree = "<group>"; };
+		BDBB658F1E256BFA001A7286 /* TestNSEnergyFormatter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSEnergyFormatter.swift; sourceTree = "<group>"; };
 		BDFDF0A61DFF5B3E00C04CC5 /* TestNSPersonNameComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSPersonNameComponents.swift; 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>"; };
@@ -1346,6 +1348,7 @@
 				2EBE67A31C77BF05006583D5 /* TestNSDateFormatter.swift */,
 				231503DA1D8AEE5D0061694D /* TestNSDecimal.swift */,
 				EA66F63D1BF1619600136161 /* TestNSDictionary.swift */,
+				BDBB658F1E256BFA001A7286 /* TestNSEnergyFormatter.swift */,
 				D512D17B1CD883F00032E6A5 /* TestNSFileHandle.swift */,
 				525AECEB1BF2C96400D15BB0 /* TestNSFileManager.swift */,
 				88D28DE61C13AE9000494606 /* TestNSGeometry.swift */,
@@ -2267,6 +2270,7 @@
 				5B13B3291C582D4C00651CE2 /* TestNSCalendar.swift in Sources */,
 				5B13B34F1C582D4C00651CE2 /* TestNSXMLParser.swift in Sources */,
 				D5C40F331CDA1D460005690C /* TestNSOperationQueue.swift in Sources */,
+				BDBB65901E256BFA001A7286 /* TestNSEnergyFormatter.swift in Sources */,
 				5B13B32F1C582D4C00651CE2 /* TestNSGeometry.swift in Sources */,
 				EA08126C1DA810BE00651B70 /* ProgressFraction.swift in Sources */,
 				5B13B3351C582D4C00651CE2 /* TestNSKeyedUnarchiver.swift in Sources */,
diff --git a/Foundation/Bridging.swift b/Foundation/Bridging.swift
index 4a6db52..b1c9525 100644
--- a/Foundation/Bridging.swift
+++ b/Foundation/Bridging.swift
@@ -121,20 +121,18 @@
     }
     
     override func isEqual(_ value: Any?) -> Bool {
-        if let other = value as? _SwiftValue {
-            if self === other {
-                return true
-            }
-            if let otherHashable = other.value as? AnyHashable,
-               let hashable = self.value as? AnyHashable {
-                return otherHashable == hashable
-            }
+        switch value {
+        case let other as _SwiftValue:
+            guard let left = other.value as? AnyHashable,
+                let right = self.value as? AnyHashable else { return self === other }
             
-        } else if let otherHashable = value as? AnyHashable,
-                  let hashable = self.value as? AnyHashable {
-            return otherHashable == hashable
+            return left == right
+        case let other as AnyHashable:
+            guard let hashable = self.value as? AnyHashable else { return false }
+            return other == hashable
+        default:
+            return false
         }
-        return false
     }
     
     public func copy(with zone: NSZone?) -> Any {
diff --git a/Foundation/Data.swift b/Foundation/Data.swift
index 5bfdfe3..0e17fc0 100644
--- a/Foundation/Data.swift
+++ b/Foundation/Data.swift
@@ -1650,7 +1650,7 @@
         
         // Minimal size data is output as an array
         if nBytes < 64 {
-            children.append((label: "bytes", value: self[0..<nBytes].map { $0 }))
+            children.append((label: "bytes", value: Array(self[0..<nBytes])))
         }
         
         let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct)
diff --git a/Foundation/IndexPath.swift b/Foundation/IndexPath.swift
index 20e5bc2..1bcf3ca 100644
--- a/Foundation/IndexPath.swift
+++ b/Foundation/IndexPath.swift
@@ -34,7 +34,7 @@
     /// Initialize with a sequence of integers.
     public init<ElementSequence : Sequence>(indexes: ElementSequence)
         where ElementSequence.Iterator.Element == Element {
-            _indexes = indexes.map { $0 }
+            _indexes = Array(indexes)
     }
     
     /// Initialize with an array literal.
@@ -159,7 +159,7 @@
             nsIndexPath.getIndexes(elementPtr, range: NSMakeRange(0, count))
             
             let buffer = UnsafeBufferPointer(start: elementPtr, count: count)
-            _indexes = buffer.map { $0 }
+            _indexes = Array(buffer)
         }
     }
     
diff --git a/Foundation/IndexSet.swift b/Foundation/IndexSet.swift
index 35d14e5..ab505a2 100644
--- a/Foundation/IndexSet.swift
+++ b/Foundation/IndexSet.swift
@@ -786,7 +786,7 @@
 
     public var customMirror: Mirror {
         var c: [(label: String?, value: Any)] = []
-        c.append((label: "ranges", value: rangeView.map { $0 }))
+        c.append((label: "ranges", value: Array(rangeView)))
         return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
     }
 }
diff --git a/Foundation/NSAffineTransform.swift b/Foundation/NSAffineTransform.swift
index 58b12c4..0b3fc61 100644
--- a/Foundation/NSAffineTransform.swift
+++ b/Foundation/NSAffineTransform.swift
@@ -334,12 +334,9 @@
     }
     
     open override func isEqual(_ object: Any?) -> Bool {
-        if let other = object as? NSAffineTransform {
-            return other === self
-                || (other.transformStruct == self.transformStruct)
-        }
-        
-        return false
+        guard let other = object as? NSAffineTransform else { return false }
+        return other === self
+            || (other.transformStruct == self.transformStruct)
     }
     
     public static var supportsSecureCoding: Bool {
diff --git a/Foundation/NSArray.swift b/Foundation/NSArray.swift
index ca1a5cb..c0a81cc 100644
--- a/Foundation/NSArray.swift
+++ b/Foundation/NSArray.swift
@@ -137,12 +137,14 @@
     }
 
     open override func isEqual(_ value: Any?) -> Bool {
-        if let other = value as? [Any] {
+        switch value {
+        case let other as [Any]:
             return self.isEqual(to: other)
-        } else if let other = value as? NSArray {
+        case let other as NSArray:
             return self.isEqual(to: other.allObjects)
+        default:
+            return false
         }
-        return false
     }
 
     open override var hash: Int {
diff --git a/Foundation/NSCalendar.swift b/Foundation/NSCalendar.swift
index d350d6f..e3b427f 100644
--- a/Foundation/NSCalendar.swift
+++ b/Foundation/NSCalendar.swift
@@ -225,15 +225,14 @@
     }
     
     open override func isEqual(_ value: Any?) -> Bool {
-        if let cal = value as? Calendar {
-            return CFEqual(_cfObject, cal._cfObject)
-        } else if let cal = value as? NSCalendar {
-            if cal === self {
-                return true
-            }
-            return CFEqual(_cfObject, cal._cfObject)
+        switch value {
+        case let other as Calendar:
+            return CFEqual(_cfObject, other._cfObject)
+        case let other as NSCalendar:
+            return other === self || CFEqual(_cfObject, other._cfObject)
+        default:
+            return false
         }
-        return false
     }
     
     open override var description: String {
@@ -1264,7 +1263,7 @@
 // or quantities of the units.
 // When you create a new one of these, all values begin Undefined.
 
-public var NSDateComponentUndefined: Int = LONG_MAX
+public var NSDateComponentUndefined: Int = Int.max
 
 open class NSDateComponents : NSObject, NSCopying, NSSecureCoding {
     internal var _calendar: Calendar?
@@ -1314,61 +1313,26 @@
     }
     
     open override func isEqual(_ object: Any?) -> Bool {
-        if let other = object as? NSDateComponents {
-            if era != other.era {
-                return false
-            }
-            if year != other.year {
-                return false
-            }
-            if quarter != other.quarter {
-                return false
-            }
-            if month != other.month {
-                return false
-            }
-            if day != other.day {
-                return false
-            }
-            if hour != other.hour {
-                return false
-            }
-            if minute != other.minute {
-                return false
-            }
-            if second != other.second {
-                return false
-            }
-            if nanosecond != other.nanosecond {
-                return false
-            }
-            if weekOfYear != other.weekOfYear {
-                return false
-            }
-            if weekOfMonth != other.weekOfMonth {
-                return false
-            }
-            if yearForWeekOfYear != other.yearForWeekOfYear {
-                return false
-            }
-            if weekday != other.weekday {
-                return false
-            }
-            if weekdayOrdinal != other.weekdayOrdinal {
-                return false
-            }
-            if isLeapMonth != other.isLeapMonth {
-                return false
-            }
-            if calendar != other.calendar {
-                return false
-            }
-            if timeZone != other.timeZone {
-                return false
-            }
-            return true
-        }
-        return false
+        guard let other = object as? NSDateComponents else { return false }
+        
+        return self === other
+            || (era == other.era
+                && year == other.year
+                && quarter == other.quarter
+                && month == other.month
+                && day == other.day
+                && hour == other.hour
+                && minute == other.minute
+                && second == other.second
+                && nanosecond == other.nanosecond
+                && weekOfYear == other.weekOfYear
+                && weekOfMonth == other.weekOfMonth
+                && yearForWeekOfYear == other.yearForWeekOfYear
+                && weekday == other.weekday
+                && weekdayOrdinal == other.weekdayOrdinal
+                && isLeapMonth == other.isLeapMonth
+                && calendar == other.calendar
+                && timeZone == other.timeZone)
     }
     
     public convenience required init?(coder aDecoder: NSCoder) {
diff --git a/Foundation/NSCharacterSet.swift b/Foundation/NSCharacterSet.swift
index 6d2e8b3..c2c72b7 100644
--- a/Foundation/NSCharacterSet.swift
+++ b/Foundation/NSCharacterSet.swift
@@ -50,12 +50,14 @@
     }
     
     open override func isEqual(_ value: Any?) -> Bool {
-        if let cs = value as? CharacterSet {
-            return CFEqual(_cfObject, cs._cfObject)
-        } else if let cs = value as? NSCharacterSet {
-            return CFEqual(_cfObject, cs._cfObject)
+        switch value {
+        case let other as CharacterSet:
+            return CFEqual(_cfObject, other._cfObject)
+        case let other as NSCharacterSet:
+            return CFEqual(_cfObject, other._cfObject)
+        default:
+            return false
         }
-        return false
     }
     
     open override var description: String {
diff --git a/Foundation/NSConcreteValue.swift b/Foundation/NSConcreteValue.swift
index e745f34..6b01414 100644
--- a/Foundation/NSConcreteValue.swift
+++ b/Foundation/NSConcreteValue.swift
@@ -167,12 +167,8 @@
     }
     
     override func isEqual(_ value: Any?) -> Bool {
-        if let other = value as? NSConcreteValue {
-            return self._typeInfo == other._typeInfo &&
-                   self._isEqualToValue(other)
-        } else {
-            return false
-        }
+        guard let other = value as? NSConcreteValue else { return false }
+        return self._typeInfo == other._typeInfo && self._isEqualToValue(other)
     }
 
     override var hash: Int {
diff --git a/Foundation/NSDate.swift b/Foundation/NSDate.swift
index 7191224..9d4793d 100644
--- a/Foundation/NSDate.swift
+++ b/Foundation/NSDate.swift
@@ -29,12 +29,14 @@
     }
     
     open override func isEqual(_ value: Any?) -> Bool {
-        if let date = value as? Date {
-            return isEqual(to: date)
-        } else if let date = value as? NSDate {
-            return isEqual(to: Date(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate))
+        switch value {
+        case let other as Date:
+            return isEqual(to: other)
+        case let other as NSDate:
+            return isEqual(to: Date(timeIntervalSinceReferenceDate: other.timeIntervalSinceReferenceDate))
+        default:
+            return false
         }
-        return false
     }
     
     deinit {
diff --git a/Foundation/NSDecimalNumber.swift b/Foundation/NSDecimalNumber.swift
index d114bf8..c540332 100644
--- a/Foundation/NSDecimalNumber.swift
+++ b/Foundation/NSDecimalNumber.swift
@@ -341,11 +341,8 @@
     }
 
     open override func isEqual(_ value: Any?) -> Bool {
-        if let number = value as? NSDecimalNumber {
-            return self.decimal == number.decimal
-        } else {
-            return false
-        }
+        guard let other = value as? NSDecimalNumber else { return false }
+        return self.decimal == other.decimal
     }
 
 }
diff --git a/Foundation/NSDictionary.swift b/Foundation/NSDictionary.swift
index e165060..defa889 100644
--- a/Foundation/NSDictionary.swift
+++ b/Foundation/NSDictionary.swift
@@ -138,16 +138,18 @@
     }
     
     public convenience init(dictionary otherDictionary: [AnyHashable : Any]) {
-        self.init(objects: otherDictionary.values.map { $0 }, forKeys: otherDictionary.keys.map { _SwiftValue.store($0) })
+        self.init(objects: Array(otherDictionary.values), forKeys: otherDictionary.keys.map { _SwiftValue.store($0) })
     }
 
     open override func isEqual(_ value: Any?) -> Bool {
-        if let other = value as? Dictionary<AnyHashable, Any> {
+        switch value {
+        case let other as Dictionary<AnyHashable, Any>:
             return isEqual(to: other)
-        } else if let other = value as? NSDictionary {
+        case let other as NSDictionary:
             return isEqual(to: Dictionary._unconditionallyBridgeFromObjectiveC(other))
+        default:
+            return false
         }
-        return false
     }
 
     open override var hash: Int {
@@ -156,7 +158,7 @@
 
     open var allKeys: [Any] {
         if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
-            return _storage.keys.map { $0 }
+            return Array(_storage.keys)
         } else {
             var keys = [Any]()
             let enumerator = keyEnumerator()
@@ -169,7 +171,7 @@
     
     open var allValues: [Any] {
         if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
-            return _storage.values.map { $0 }
+            return Array(_storage.values)
         } else {
             var values = [Any]()
             let enumerator = keyEnumerator()
diff --git a/Foundation/NSEnergyFormatter.swift b/Foundation/NSEnergyFormatter.swift
index 1229f59..2d1c7c3 100644
--- a/Foundation/NSEnergyFormatter.swift
+++ b/Foundation/NSEnergyFormatter.swift
@@ -7,41 +7,195 @@
 // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
 //
 
-
 extension EnergyFormatter {
-    public enum Unit : Int {
+    public enum Unit: Int {
+
+        case joule = 11
+        case kilojoule = 14
+        case calorie = 1793 // chemistry "calories", abbr "cal"
+        case kilocalorie = 1794 // kilocalories in general, abbr “kcal”, or “C” in some locales (e.g. US) when usesFoodEnergy is set to YES
+
+        // Map Unit to UnitEnergy class to aid with conversions
+        fileprivate var unitEnergy: UnitEnergy {
+            switch self {
+            case .joule:
+                return UnitEnergy.joules
+            case .kilojoule:
+                return UnitEnergy.kilojoules
+            case .calorie:
+                return UnitEnergy.calories
+            case .kilocalorie:
+                return UnitEnergy.kilocalories
+            }
+        }
+
+        // Reuse symbols defined in UnitEnergy, except for kilocalories, which is defined as "kCal"
+        fileprivate var symbol: String {
+            switch self {
+            case .kilocalorie:
+                return "kcal"
+            default:
+                return unitEnergy.symbol
+            }
+        }
+
+        // Return singular, full string representation of the energy unit
+        fileprivate var singularString: String {
+            switch self {
+            case .joule:
+                return "joule"
+            case .kilojoule:
+                return "kilojoule"
+            case .calorie:
+                return "calorie"
+            case .kilocalorie:
+                return "kilocalorie"
+            }
+        }
         
-        case joule
-        case kilojoule
-        case calorie // chemistry "calories", abbr "cal"
-        case kilocalorie // kilocalories in general, abbr “kcal”, or “C” in some locales (e.g. US) when usesFoodEnergy is set to YES
+        // Return plural, full string representation of the energy unit
+        fileprivate var pluralString: String {
+            return "\(self.singularString)s"
+        }
     }
 }
 
-open class EnergyFormatter : Formatter {
-    
-    public required init?(coder: NSCoder) {
-        NSUnimplemented()
+open class EnergyFormatter: Formatter {
+
+    public override init() {
+        numberFormatter = NumberFormatter()
+        numberFormatter.numberStyle = .decimal
+        unitStyle = .medium
+        isForFoodEnergyUse = false
+        super.init()
     }
-    
+
+    public required init?(coder: NSCoder) {
+        numberFormatter = NumberFormatter()
+        numberFormatter.numberStyle = .decimal
+        unitStyle = .medium
+        isForFoodEnergyUse = false
+        super.init()
+    }
+
     /*@NSCopying*/ open var numberFormatter: NumberFormatter! // default is NSNumberFormatter with NSNumberFormatterDecimalStyle
     open var unitStyle: UnitStyle // default is NSFormattingUnitStyleMedium
     open var isForFoodEnergyUse: Bool // default is NO; if it is set to YES, NSEnergyFormatterUnitKilocalorie may be “C” instead of “kcal"
-    
+
     // Format a combination of a number and an unit to a localized string.
-    open func string(fromValue value: Double, unit: Unit) -> String { NSUnimplemented() }
-    
+    open func string(fromValue value: Double, unit: Unit) -> String {
+        guard let formattedValue = numberFormatter.string(from:NSNumber(value: value)) else {
+            fatalError("Cannot format \(value) as string")
+        }
+        
+        let separator = unitStyle == EnergyFormatter.UnitStyle.short ? "" : " "
+        return "\(formattedValue)\(separator)\(unitString(fromValue: value, unit: unit))"
+    }
+
     // Format a number in joules to a localized string with the locale-appropriate unit and an appropriate scale (e.g. 10.3J = 2.46cal in the US locale).
-    open func string(fromJoules numberInJoules: Double) -> String { NSUnimplemented() }
-    
+    open func string(fromJoules numberInJoules: Double) -> String {
+
+        //Convert to the locale-appropriate unit
+        var unitFromJoules: EnergyFormatter.Unit = .joule
+        _ = self.unitString(fromJoules: numberInJoules, usedUnit: &unitFromJoules)
+
+        //Map the unit to UnitLength type for conversion later
+        let unitEnergyFromJoules = unitFromJoules.unitEnergy
+
+        //Create a measurement object based on the value in joules
+        let joulesMeasurement = Measurement<UnitEnergy>(value:numberInJoules, unit: .joules)
+
+        //Convert the object to the locale-appropriate unit determined above
+        let unitMeasurement = joulesMeasurement.converted(to: unitEnergyFromJoules)
+
+        //Extract the number from the measurement
+        let numberInUnit = unitMeasurement.value
+
+        return string(fromValue: numberInUnit, unit: unitFromJoules)
+    }
+
     // Return a localized string of the given unit, and if the unit is singular or plural is based on the given number.
-    open func unitString(fromValue value: Double, unit: Unit) -> String { NSUnimplemented() }
-    
+    open func unitString(fromValue value: Double, unit: Unit) -> String {
+        
+        //Special case when isForFoodEnergyUse is true
+        if isForFoodEnergyUse && unit == .kilocalorie {
+            if unitStyle == .short {
+                return "C"
+            } else if unitStyle == .medium {
+                return "Cal"
+            } else {
+                return "Calories"
+            }
+        }
+        
+        if unitStyle == .short || unitStyle == .medium {
+            return unit.symbol
+        } else if value == 1.0 {
+            return unit.singularString
+        } else {
+            return unit.pluralString
+        }
+    }
+
     // Return the locale-appropriate unit, the same unit used by -stringFromJoules:.
-    open func unitString(fromJoules numberInJoules: Double, usedUnit unitp: UnsafeMutablePointer<Unit>?) -> String { NSUnimplemented() }
-    
-    
+    open func unitString(fromJoules numberInJoules: Double, usedUnit unitp: UnsafeMutablePointer<Unit>?) -> String {
+
+        //Convert to the locale-appropriate unit
+        let unitFromJoules: Unit
+
+        if numberFormatter.locale.usesCalories {
+            if numberInJoules > 0 && numberInJoules <= 4184 {
+                unitFromJoules = .calorie
+            } else {
+                unitFromJoules = .kilocalorie
+            }
+        } else {
+            if numberInJoules > 0 && numberInJoules <= 1000 {
+                unitFromJoules = .joule
+            } else {
+                unitFromJoules = .kilojoule
+            }
+        }
+        unitp?.pointee = unitFromJoules
+
+        //Map the unit to UnitEnergy type for conversion later
+        let unitEnergyFromJoules = unitFromJoules.unitEnergy
+
+        //Create a measurement object based on the value in joules
+        let joulesMeasurement = Measurement<UnitEnergy>(value:numberInJoules, unit: .joules)
+
+        //Convert the object to the locale-appropriate unit determined above
+        let unitMeasurement = joulesMeasurement.converted(to: unitEnergyFromJoules)
+
+        //Extract the number from the measurement
+        let numberInUnit = unitMeasurement.value
+
+        //Return the appropriate representation of the unit based on the selected unit style
+        return unitString(fromValue: numberInUnit, unit: unitFromJoules)
+    }
+
     /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
     /// - Note: Since this API is under consideration it may be either removed or revised in the near future
     open override func objectValue(_ string: String) throws -> Any? { return nil }
 }
+
+/// TODO: Replace calls to the below function to use Locale.regionCode
+/// Temporary workaround due to unpopulated Locale attributes
+/// See https://bugs.swift.org/browse/SR-3202
+extension Locale {
+    public var usesCalories: Bool {
+
+        switch self.identifier {
+        case "en_US": return true
+        case "en_US_POSIX": return true
+        case "haw_US": return true
+        case "es_US": return true
+        case "chr_US": return true
+        case "en_GB": return true
+        case "kw_GB": return true
+        case "cy_GB": return true
+        case "gv_GB": return true
+        default: return false
+        }
+    }
+}
diff --git a/Foundation/NSError.swift b/Foundation/NSError.swift
index 3c6e255..c83403e 100644
--- a/Foundation/NSError.swift
+++ b/Foundation/NSError.swift
@@ -144,14 +144,14 @@
         return userInfo[NSHelpAnchorErrorKey] as? String
     }
     
-    internal typealias NSErrorProvider = (_ error: NSError, _ key: String) -> Any?
-    internal static var userInfoProviders = [String: NSErrorProvider]()
+    internal typealias UserInfoProvider = (_ error: Error, _ key: String) -> Any?
+    internal static var userInfoProviders = [String: UserInfoProvider]()
     
-    open class func setUserInfoValueProvider(forDomain errorDomain: String, provider: (/* @escaping */ (NSError, String) -> Any?)?) {
+    open class func setUserInfoValueProvider(forDomain errorDomain: String, provider: (/* @escaping */ (Error, String) -> Any?)?) {
         NSError.userInfoProviders[errorDomain] = provider
     }
 
-    open class func userInfoValueProvider(forDomain errorDomain: String) -> ((NSError, String) -> Any?)? {
+    open class func userInfoValueProvider(forDomain errorDomain: String) -> ((Error, String) -> Any?)? {
         return NSError.userInfoProviders[errorDomain]
     }
     
@@ -169,11 +169,8 @@
     
     override open func isEqual(_ object: Any?) -> Bool {
         // Pulled from NSObject itself; this works on all platforms.
-        if let obj = object as? NSError {
-            return obj === self
-        }
-        
-        return false
+        guard let obj = object as? NSError else { return false }
+        return obj === self
     }
 }
 
diff --git a/Foundation/NSLocale.swift b/Foundation/NSLocale.swift
index f556df2..52becd1 100644
--- a/Foundation/NSLocale.swift
+++ b/Foundation/NSLocale.swift
@@ -236,12 +236,14 @@
 }
 
 
-public func ==(_ lhs: NSLocale.Key, _ rhs: NSLocale.Key) -> Bool {
-    return lhs.rawValue == rhs.rawValue
-}
+extension NSLocale.Key {
+    public static func ==(_ lhs: NSLocale.Key, _ rhs: NSLocale.Key) -> Bool {
+        return lhs.rawValue == rhs.rawValue
+    }
 
-public func <(_ lhs: NSLocale.Key, _ rhs: NSLocale.Key) -> Bool {
-    return lhs.rawValue < rhs.rawValue
+    public static func <(_ lhs: NSLocale.Key, _ rhs: NSLocale.Key) -> Bool {
+        return lhs.rawValue < rhs.rawValue
+    }
 }
 
 
diff --git a/Foundation/NSNumber.swift b/Foundation/NSNumber.swift
index e7334ef..854f4ac 100644
--- a/Foundation/NSNumber.swift
+++ b/Foundation/NSNumber.swift
@@ -212,16 +212,18 @@
     }
     
     open override func isEqual(_ value: Any?) -> Bool {
-        if let number = value as? Int {
-            return intValue == number
-        } else if let number = value as? Double {
-            return doubleValue == number
-        } else if let number = value as? Bool {
-            return boolValue == number
-        } else if let number = value as? NSNumber {
-            return CFEqual(_cfObject, number._cfObject)
+        switch value {
+        case let other as Int:
+            return intValue == other
+        case let other as Double:
+            return doubleValue == other
+        case let other as Bool:
+            return boolValue == other
+        case let other as NSNumber:
+            return CFEqual(_cfObject, other._cfObject)
+        default:
+            return false
         }
-        return false
     }
 
     open override var objCType: UnsafePointer<Int8> {
diff --git a/Foundation/NSObject.swift b/Foundation/NSObject.swift
index 4b8a58a..2c5956f 100644
--- a/Foundation/NSObject.swift
+++ b/Foundation/NSObject.swift
@@ -186,10 +186,8 @@
     /// - Parameter object: The object with which to compare the instance.
     /// - Returns:          `true` if the instance is equal to `object`, otherwise `false`.
     open func isEqual(_ object: Any?) -> Bool {
-        if let obj = object as? NSObject {
-            return obj === self
-        }
-        return false
+        guard let obj = object as? NSObject else { return false }
+        return obj === self
     }
     
     /// Returns an integer that can be used as a table address in a hash table structure.
@@ -323,18 +321,18 @@
     open var hashValue: Int {
         return hash
     }
-}
 
-/// Returns a Boolean value indicating whether two values are equal.
-///
-/// Equality is the inverse of inequality. For any values `a` and `b`,
-/// `a == b` implies that `a != b` is `false`.
-///
-/// - Parameters:
-///   - lhs: A value to compare.
-///   - rhs: Another value to compare.
-public func ==(lhs: NSObject, rhs: NSObject) -> Bool {
-    return lhs.isEqual(rhs)
+    /// Returns a Boolean value indicating whether two values are equal.
+    ///
+    /// Equality is the inverse of inequality. For any values `a` and `b`,
+    /// `a == b` implies that `a != b` is `false`.
+    ///
+    /// - Parameters:
+    ///   - lhs: A value to compare.
+    ///   - rhs: Another value to compare.
+    public static func ==(lhs: NSObject, rhs: NSObject) -> Bool {
+        return lhs.isEqual(rhs)
+    }
 }
 
 extension NSObject : CustomDebugStringConvertible {
diff --git a/Foundation/NSOrderedSet.swift b/Foundation/NSOrderedSet.swift
index b1001ed..33b5f4e 100644
--- a/Foundation/NSOrderedSet.swift
+++ b/Foundation/NSOrderedSet.swift
@@ -33,11 +33,8 @@
     }
     
     open override func isEqual(_ object: Any?) -> Bool {
-        if let orderedSet = object as? NSOrderedSet {
-            return isEqual(to: orderedSet)
-        } else {
-            return false
-        }
+        guard let orderedSet = object as? NSOrderedSet else { return false }
+        return isEqual(to: orderedSet)
     }
     
     open func encode(with aCoder: NSCoder) {
@@ -295,7 +292,7 @@
 
     public convenience init(orderedSet set: NSOrderedSet, range: NSRange, copyItems flag: Bool) {
         // TODO: Use the array method here when available.
-        self.init(array: set.map { $0 }, range: range, copyItems: flag)
+        self.init(array: Array(set), range: range, copyItems: flag)
     }
 
     public convenience init(array: [Any]) {
@@ -331,7 +328,7 @@
     }
 
     public convenience init(set: Set<AnyHashable>, copyItems flag: Bool) {
-        self.init(array: set.map { $0 }, copyItems: flag)
+        self.init(array: Array(set), copyItems: flag)
     }
 }
 
diff --git a/Foundation/NSPredicate.swift b/Foundation/NSPredicate.swift
index 3aada9c..b5b4642 100644
--- a/Foundation/NSPredicate.swift
+++ b/Foundation/NSPredicate.swift
@@ -73,25 +73,23 @@
     }
     
     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
-                }
+        guard let other = object as? NSPredicate else { return false }
+        
+        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
diff --git a/Foundation/NSRange.swift b/Foundation/NSRange.swift
index 8b0dff8..3cfc2cc 100644
--- a/Foundation/NSRange.swift
+++ b/Foundation/NSRange.swift
@@ -87,7 +87,7 @@
     static func objCType() -> String {
 #if arch(i386) || arch(arm)
         return "{_NSRange=II}"
-#elseif arch(x86_64) || arch(arm64) || arch(s390x)
+#elseif arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
         return "{_NSRange=QQ}"
 #else
         NSUnimplemented()
diff --git a/Foundation/NSRegularExpression.swift b/Foundation/NSRegularExpression.swift
index 0ad9579..0d1a289 100644
--- a/Foundation/NSRegularExpression.swift
+++ b/Foundation/NSRegularExpression.swift
@@ -139,8 +139,8 @@
 
 internal class _NSRegularExpressionMatcher {
     var regex: NSRegularExpression
-    var block: (TextCheckingResult?, NSMatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void
-    init(regex: NSRegularExpression, block: @escaping (TextCheckingResult?, NSMatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void) {
+    var block: (NSTextCheckingResult?, NSMatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void
+    init(regex: NSRegularExpression, block: @escaping (NSTextCheckingResult?, NSMatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void) {
         self.regex = regex
         self.block = block
     }
@@ -159,7 +159,7 @@
         })
     } else {
         let result = ranges!.withMemoryRebound(to: NSRange.self, capacity: count) { rangePtr in
-            TextCheckingResult.regularExpressionCheckingResultWithRanges(rangePtr, count: count, regularExpression: matcher.regex)
+            NSTextCheckingResult.regularExpressionCheckingResultWithRanges(rangePtr, count: count, regularExpression: matcher.regex)
         }
 #if os(OSX) || os(iOS)
         let flags = NSMatchingFlags(rawValue: options.rawValue)
@@ -177,7 +177,7 @@
     /* The fundamental matching method on NSRegularExpression is a block iterator.  There are several additional convenience methods, for returning all matches at once, the number of matches, the first match, or the range of the first match.  Each match is specified by an instance of NSTextCheckingResult (of type NSTextCheckingTypeRegularExpression) in which the overall match range is given by the range property (equivalent to range at:0) and any capture group ranges are given by range at: for indexes from 1 to numberOfCaptureGroups.  {NSNotFound, 0} is used if a particular capture group does not participate in the match.
     */
     
-    public func enumerateMatches(in string: String, options: NSMatchingOptions, range: NSRange, using block: @escaping (TextCheckingResult?, NSMatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
+    public func enumerateMatches(in string: String, options: NSMatchingOptions, range: NSRange, using block: @escaping (NSTextCheckingResult?, NSMatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
         let matcher = _NSRegularExpressionMatcher(regex: self, block: block)
         withExtendedLifetime(matcher) { (m: _NSRegularExpressionMatcher) -> Void in
 #if os(OSX) || os(iOS)
@@ -189,9 +189,9 @@
         }
     }
     
-    public func matches(in string: String, options: NSMatchingOptions, range: NSRange) -> [TextCheckingResult] {
-        var matches = [TextCheckingResult]()
-        enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: TextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
+    public func matches(in string: String, options: NSMatchingOptions, range: NSRange) -> [NSTextCheckingResult] {
+        var matches = [NSTextCheckingResult]()
+        enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: NSTextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
             if let match = result {
                 matches.append(match)
             }
@@ -208,9 +208,9 @@
         return count
     }
     
-    public func firstMatch(in string: String, options: NSMatchingOptions, range: NSRange) -> TextCheckingResult? {
-        var first: TextCheckingResult?
-        enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: TextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
+    public func firstMatch(in string: String, options: NSMatchingOptions, range: NSRange) -> NSTextCheckingResult? {
+        var first: NSTextCheckingResult?
+        enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: NSTextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
             first = result
             stop.pointee = true
         }
@@ -219,7 +219,7 @@
     
     public func rangeOfFirstMatch(in string: String, options: NSMatchingOptions, range: NSRange) -> NSRange {
         var firstRange = NSMakeRange(NSNotFound, 0)
-        enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: TextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
+        enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: NSTextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
             if let match = result {
                 firstRange = match.range
             } else {
@@ -290,7 +290,7 @@
     
     /* For clients implementing their own replace functionality, this is a method to perform the template substitution for a single result, given the string from which the result was matched, an offset to be added to the location of the result in the string (for example, in case modifications to the string moved the result since it was matched), and a replacement template.
     */
-    public func replacementString(for result: TextCheckingResult, in string: String, offset: Int, template templ: String) -> String {
+    public func replacementString(for result: NSTextCheckingResult, in string: String, offset: Int, template templ: String) -> String {
         // ??? need to consider what happens if offset takes range out of bounds due to replacement
         struct once {
             static let characterSet = CharacterSet(charactersIn: "\\$")
diff --git a/Foundation/NSSet.swift b/Foundation/NSSet.swift
index 61c3ba1..fdd5b99 100644
--- a/Foundation/NSSet.swift
+++ b/Foundation/NSSet.swift
@@ -114,12 +114,14 @@
     }
 
     open override func isEqual(_ value: Any?) -> Bool {
-        if let other = value as? Set<AnyHashable> {
+        switch value {
+        case let other as Set<AnyHashable>:
             return isEqual(to: other)
-        } else if let other = value as? NSSet {
+        case let other as NSSet:
             return isEqual(to: Set._unconditionallyBridgeFromObjectiveC(other))
+        default:
+            return false
         }
-        return false
     }
 
     open override var hash: Int {
@@ -150,7 +152,7 @@
                 }
             })
         } else {
-            self.init(array: set.map { $0 })
+            self.init(array: Array(set))
         }
     }
 }
@@ -421,7 +423,7 @@
     }
 
     public convenience init(set: Set<AnyHashable>) {
-        self.init(array: set.map { $0 })
+        self.init(array: Array(set))
     }
 
     public required convenience init?(coder: NSCoder) { NSUnimplemented() }
diff --git a/Foundation/NSSpecialValue.swift b/Foundation/NSSpecialValue.swift
index af88300..42bc6d9 100644
--- a/Foundation/NSSpecialValue.swift
+++ b/Foundation/NSSpecialValue.swift
@@ -134,14 +134,14 @@
     }
     
     override func isEqual(_ value: Any?) -> Bool {
-        if let object = value as? NSObject {
-            if self === object {
-                return true
-            } else if let special = object as? NSSpecialValue {
-                return _value.isEqual(special._value)
-            }
+        switch value {
+        case let other as NSSpecialValue:
+            return _value.isEqual(other._value)
+        case let other as NSObject:
+            return self === other
+        default:
+            return false
         }
-        return false
     }
     
     override var hash: Int {
diff --git a/Foundation/NSSwiftRuntime.swift b/Foundation/NSSwiftRuntime.swift
index 116ff78..55e3279 100644
--- a/Foundation/NSSwiftRuntime.swift
+++ b/Foundation/NSSwiftRuntime.swift
@@ -39,10 +39,8 @@
     }
     
     override func isEqual(_ value: Any?) -> Bool {
-        if let other = value as? NSObject {
-            return CFEqual(self, other)
-        }
-        return false
+        guard let other = value as? NSObject else { return false }
+        return CFEqual(self, other)
     }
     
     override var description: String {
diff --git a/Foundation/NSTextCheckingResult.swift b/Foundation/NSTextCheckingResult.swift
index b8c2c09..caed9a8 100644
--- a/Foundation/NSTextCheckingResult.swift
+++ b/Foundation/NSTextCheckingResult.swift
@@ -10,7 +10,7 @@
 import CoreFoundation
 
 /* NSTextCheckingType in this project is limited to regular expressions. */
-extension TextCheckingResult {
+extension NSTextCheckingResult {
     public struct CheckingType : OptionSet {
         public let rawValue: UInt64
         public init(rawValue: UInt64) { self.rawValue = rawValue }
@@ -19,22 +19,26 @@
     }
 }
 
-open class TextCheckingResult: NSObject, NSCopying, NSCoding {
+open class NSTextCheckingResult: NSObject, NSCopying, NSCoding {
     
     public override init() {
-        super.init()
+        if type(of: self) == NSTextCheckingResult.self {
+            NSRequiresConcreteImplementation()
+        }
     }
     
-    open class func regularExpressionCheckingResultWithRanges(_ ranges: NSRangePointer, count: Int, regularExpression: NSRegularExpression) -> TextCheckingResult {
-        return _NSRegularExpressionTextCheckingResultResult(ranges: ranges, count: count, regularExpression: regularExpression)
+    open class func regularExpressionCheckingResultWithRanges(_ ranges: NSRangePointer, count: Int, regularExpression: NSRegularExpression) -> NSTextCheckingResult {
+        return _NSRegularExpressionNSTextCheckingResultResult(ranges: ranges, count: count, regularExpression: regularExpression)
     }
 
     public required init?(coder aDecoder: NSCoder) {
-        NSUnimplemented()
+        if type(of: self) == NSTextCheckingResult.self {
+            NSRequiresConcreteImplementation()
+        }
     }
     
     open func encode(with aCoder: NSCoder) {
-        NSUnimplemented()
+        NSRequiresConcreteImplementation()
     }
     
     open override func copy() -> Any {
@@ -42,21 +46,22 @@
     }
     
     open func copy(with zone: NSZone? = nil) -> Any {
-        NSUnimplemented()
+        return self
     }
     
     /* Mandatory properties, used with all types of results. */
-    open var resultType: CheckingType { NSUnimplemented() }
+    open var resultType: CheckingType { NSRequiresConcreteImplementation() }
     open var range: NSRange { return range(at: 0) }
     /* A result must have at least one range, but may optionally have more (for example, to represent regular expression capture groups).  The range at index 0 always matches the range property.  Additional ranges, if any, will have indexes from 1 to numberOfRanges-1. */
-    open func range(at idx: Int) -> NSRange { NSUnimplemented() }
+    open func range(at idx: Int) -> NSRange { NSRequiresConcreteImplementation() }
     open var regularExpression: NSRegularExpression? { return nil }
     open var numberOfRanges: Int { return 1 }
 }
 
-internal class _NSRegularExpressionTextCheckingResultResult : TextCheckingResult {
+internal class _NSRegularExpressionNSTextCheckingResultResult : NSTextCheckingResult {
     var _ranges = [NSRange]()
     let _regularExpression: NSRegularExpression
+    
     init(ranges: NSRangePointer, count: Int, regularExpression: NSRegularExpression) {
         _regularExpression = regularExpression
         super.init()
@@ -67,7 +72,11 @@
     }
 
     internal required init?(coder aDecoder: NSCoder) {
-        fatalError("init(coder:) has not been implemented")
+        NSUnimplemented()
+    }
+    
+    internal override func encode(with aCoder: NSCoder) {
+        NSUnimplemented()
     }
     
     override var resultType: CheckingType { return .RegularExpression }
@@ -76,9 +85,9 @@
     override var regularExpression: NSRegularExpression? { return _regularExpression }
 }
 
-extension TextCheckingResult {
+extension NSTextCheckingResult {
     
-    public func resultByAdjustingRangesWithOffset(_ offset: Int) -> TextCheckingResult {
+    public func resultByAdjustingRangesWithOffset(_ offset: Int) -> NSTextCheckingResult {
         let count = self.numberOfRanges
         var newRanges = [NSRange]()
         for idx in 0..<count {
@@ -91,7 +100,7 @@
               newRanges.append(NSRange(location: currentRange.location + offset,length: currentRange.length))
            }
         }
-        let result = TextCheckingResult.regularExpressionCheckingResultWithRanges(&newRanges, count: count, regularExpression: self.regularExpression!)
+        let result = NSTextCheckingResult.regularExpressionCheckingResultWithRanges(&newRanges, count: count, regularExpression: self.regularExpression!)
         return result
     }
 }
diff --git a/Foundation/NSThread.swift b/Foundation/NSThread.swift
index 683dcf5..80b4d4c 100644
--- a/Foundation/NSThread.swift
+++ b/Foundation/NSThread.swift
@@ -89,8 +89,8 @@
         var ti = end_at - start_at
         let end_ut = start_ut + ti
         while (0.0 < ti) {
-            var __ts__ = timespec(tv_sec: LONG_MAX, tv_nsec: 0)
-            if ti < Double(LONG_MAX) {
+            var __ts__ = timespec(tv_sec: Int.max, tv_nsec: 0)
+            if ti < Double(Int.max) {
                 var integ = 0.0
                 let frac: Double = withUnsafeMutablePointer(to: &integ) { integp in
                     return modf(ti, integp)
@@ -110,8 +110,8 @@
         let start_ut = CFGetSystemUptime()
         let end_ut = start_ut + ti
         while 0.0 < ti {
-            var __ts__ = timespec(tv_sec: LONG_MAX, tv_nsec: 0)
-            if ti < Double(LONG_MAX) {
+            var __ts__ = timespec(tv_sec: Int.max, tv_nsec: 0)
+            if ti < Double(Int.max) {
                 var integ = 0.0
                 let frac: Double = withUnsafeMutablePointer(to: &integ) { integp in
                     return modf(ti, integp)
@@ -143,7 +143,6 @@
 #endif
     internal var _status = _NSThreadStatus.initialized
     internal var _cancelled = false
-    internal var _name: String?
     /// - Note: this differs from the Darwin implementation in that the keys must be Strings
     open var threadDictionary = [String : Any]()
     
@@ -192,14 +191,9 @@
     }
     
     open var name: String? {
-        get {
-            return _name
-        }
-        set {
-            _name = newValue
-
+        didSet {
             if _thread == Thread.current._thread {
-                _CFThreadSetName(_name)
+                _CFThreadSetName(name)
             }
         }
     }
diff --git a/Foundation/NSTimeZone.swift b/Foundation/NSTimeZone.swift
index a8d7227..f022dfa 100644
--- a/Foundation/NSTimeZone.swift
+++ b/Foundation/NSTimeZone.swift
@@ -54,11 +54,8 @@
     }
     
     open override func isEqual(_ object: Any?) -> Bool {
-        if let tz = object as? NSTimeZone {
-            return isEqual(to: tz._swiftObject)
-        } else {
-            return false
-        }
+        guard let other = object as? NSTimeZone else { return false }
+        return isEqual(to: other._swiftObject)
     }
     
     open override var description: String {
diff --git a/Foundation/NSURL.swift b/Foundation/NSURL.swift
index d6f3207..7c74030 100644
--- a/Foundation/NSURL.swift
+++ b/Foundation/NSURL.swift
@@ -257,11 +257,8 @@
     }
     
     open override func isEqual(_ object: Any?) -> Bool {
-        if let url = object as? NSURL {
-            return CFEqual(_cfObject, url._cfObject)
-        } else {
-            return false
-        }
+        guard let other = object as? NSURL else { return false }
+        return CFEqual(_cfObject, other._cfObject)
     }
     
     open override var description: String {
@@ -940,13 +937,10 @@
     }
     
     open override func isEqual(_ object: Any?) -> Bool {
-        if let other = object as? NSURLQueryItem {
-            return other === self
+        guard let other = object as? NSURLQueryItem else { return false }
+        return other === self
                 || (other.name == self.name
                     && other.value == self.value)
-        }
-        
-        return false
     }
     
     open let name: String
@@ -961,34 +955,16 @@
     }
 
     open override func isEqual(_ object: Any?) -> Bool {
-        if let other = object as? NSURLComponents {
-            if scheme != other.scheme {
-                return false
-            }
-            if user != other.user {
-                return false
-            }
-            if password != other.password {
-                return false
-            }
-            if host != other.host {
-                return false
-            }
-            if port != other.port {
-                return false
-            }
-            if path != other.path {
-                return false
-            }
-            if query != other.query {
-                return false
-            }
-            if fragment != other.fragment {
-                return false
-            }
-            return true
-        }
-        return false
+        guard let other = object as? NSURLComponents else { return false }
+        return self === other
+            || (scheme == other.scheme
+                && user == other.user
+                && password == other.password
+                && host == other.host
+                && port == other.port
+                && path == other.path
+                && query == other.query
+                && fragment == other.fragment)
     }
 
     open func copy(with zone: NSZone? = nil) -> Any {
diff --git a/Foundation/NSURLCredential.swift b/Foundation/NSURLCredential.swift
index 32cd075..319bdaa 100644
--- a/Foundation/NSURLCredential.swift
+++ b/Foundation/NSURLCredential.swift
@@ -106,14 +106,11 @@
     }
     
     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
+        guard let other = object as? URLCredential else { return false }
+        return other === self
+            || (other._user == self._user
+                && other._password == self._password
+                && other._persistence == self._persistence)
     }
     
     /*!
diff --git a/Foundation/NSURLRequest.swift b/Foundation/NSURLRequest.swift
index 438aa6d..0e143f2 100644
--- a/Foundation/NSURLRequest.swift
+++ b/Foundation/NSURLRequest.swift
@@ -240,17 +240,15 @@
         //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
+        guard let other = object as? NSURLRequest else { return false }
+        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)
     }
     
     /// Indicates that NSURLRequest implements the NSSecureCoding protocol.
diff --git a/Foundation/NSURLSession/NSURLSessionTask.swift b/Foundation/NSURLSession/NSURLSessionTask.swift
index 6f33cc6..5856d5d 100644
--- a/Foundation/NSURLSession/NSURLSessionTask.swift
+++ b/Foundation/NSURLSession/NSURLSessionTask.swift
@@ -194,8 +194,18 @@
      * cases, the task may signal other work before it acknowledges the
      * cancelation.  -cancel may be sent to a task that has been suspended.
      */
-    open func cancel() { NSUnimplemented() }
-    
+    open func cancel() {
+        workQueue.sync {
+            guard self.state == .running || self.state == .suspended else { return }
+            self.state = .canceling
+            self.workQueue.async {
+                self.internalState = .transferFailed
+                let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
+                self.completeTask(withError: urlError)
+            }
+        }
+    }
+
     /*
      * The current state of the task within the session.
      */
@@ -866,7 +876,7 @@
     }
     func completeTask(withError error: Error) {
         self.error = error
-        
+
         guard case .transferFailed = internalState else {
             fatalError("Trying to complete the task, but its transfer isn't complete / failed.")
         }
diff --git a/Foundation/NSUUID.swift b/Foundation/NSUUID.swift
index e43e06b..37126eb 100644
--- a/Foundation/NSUUID.swift
+++ b/Foundation/NSUUID.swift
@@ -78,7 +78,8 @@
     }
     
     open override func isEqual(_ value: Any?) -> Bool {
-        if let other = value as? UUID {
+        switch value {
+        case let other as UUID:
             return other.uuid.0 == buffer[0] &&
                 other.uuid.1 == buffer[1] &&
                 other.uuid.2 == buffer[2] &&
@@ -95,13 +96,11 @@
                 other.uuid.13 == buffer[13] &&
                 other.uuid.14 == buffer[14] &&
                 other.uuid.15 == buffer[15]
-        } else if let other = value as? NSUUID {
-            if other === self {
-                return true
-            }
-            return _cf_uuid_compare(buffer, other.buffer) == 0
+        case let other as NSUUID:
+            return other === self || _cf_uuid_compare(buffer, other.buffer) == 0
+        default:
+            return false
         }
-        return false
     }
     
     open override var hash: Int {
diff --git a/Foundation/NSValue.swift b/Foundation/NSValue.swift
index 685923b..5ef72d9 100644
--- a/Foundation/NSValue.swift
+++ b/Foundation/NSValue.swift
@@ -52,21 +52,19 @@
     }
     
     open override func isEqual(_ value: Any?) -> Bool {
-        if let object = value as? NSValue {
-            if self === object {
-                return true
-            } else {
-                // bypass _concreteValue accessor in order to avoid acquiring lock twice
-                let (lhs, rhs) = NSValue.SideTableLock.synchronized {
-                    return (NSValue.SideTable[ObjectIdentifier(self)],
-                            NSValue.SideTable[ObjectIdentifier(object)])
-                }
-                if let lhs = lhs, let rhs = rhs {
-                    return lhs.isEqual(rhs)
-                }
+        guard let object = value as? NSValue else { return false }
+        
+        if self === object {
+            return true
+        } else {
+            // bypass _concreteValue accessor in order to avoid acquiring lock twice
+            let (lhs, rhs) = NSValue.SideTableLock.synchronized {
+                return (NSValue.SideTable[ObjectIdentifier(self)],
+                        NSValue.SideTable[ObjectIdentifier(object)])
             }
+            guard let left = lhs, let right = rhs else { return false }
+            return left.isEqual(right)
         }
-        return false
     }
     
     open override var description : String {
diff --git a/Foundation/URLComponents.swift b/Foundation/URLComponents.swift
index c79e17b..fdf6d95 100644
--- a/Foundation/URLComponents.swift
+++ b/Foundation/URLComponents.swift
@@ -272,8 +272,8 @@
     ///
     /// - note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a `URLQueryItem` with a zero-length name and and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value.
     public var queryItems: [URLQueryItem]? {
-        get { return _handle.map { $0.queryItems?.map { return $0 as URLQueryItem } } }
-        set { _applyMutation { $0.queryItems = newValue?.map { $0 } } }
+        get { return _handle.map { $0.queryItems } }
+        set { _applyMutation { $0.queryItems = newValue } }
     }
     
     public var hashValue: Int {
diff --git a/TestFoundation/TestNSArray.swift b/TestFoundation/TestNSArray.swift
index c905e52..50a6a96 100644
--- a/TestFoundation/TestNSArray.swift
+++ b/TestFoundation/TestNSArray.swift
@@ -400,7 +400,7 @@
         }
         mutableStringsInput1.sort(comparator)
         mutableStringsInput2.sort(options: [], usingComparator: comparator)
-        XCTAssertTrue(mutableStringsInput1.isEqual(to: mutableStringsInput2.map { $0 }))
+        XCTAssertTrue(mutableStringsInput1.isEqual(to: Array(mutableStringsInput2)))
     }
 
     func test_equality() {
@@ -410,14 +410,14 @@
 
         XCTAssertTrue(array1 == array2)
         XCTAssertTrue(array1.isEqual(array2))
-        XCTAssertTrue(array1.isEqual(to: array2.map { $0 }))
+        XCTAssertTrue(array1.isEqual(to: Array(array2)))
         // if 2 arrays are equal, hashes should be equal as well. But not vise versa
         XCTAssertEqual(array1.hash, array2.hash)
         XCTAssertEqual(array1.hashValue, array2.hashValue)
 
         XCTAssertFalse(array1 == array3)
         XCTAssertFalse(array1.isEqual(array3))
-        XCTAssertFalse(array1.isEqual(to: array3.map { $0 }))
+        XCTAssertFalse(array1.isEqual(to: Array(array3)))
 
         XCTAssertFalse(array1.isEqual(nil))
         XCTAssertFalse(array1.isEqual(NSObject()))
diff --git a/TestFoundation/TestNSEnergyFormatter.swift b/TestFoundation/TestNSEnergyFormatter.swift
new file mode 100644
index 0000000..f07bd03
--- /dev/null
+++ b/TestFoundation/TestNSEnergyFormatter.swift
@@ -0,0 +1,148 @@
+// 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 TestNSEnergyFormatter: XCTestCase {
+    let formatter: EnergyFormatter = EnergyFormatter()
+    
+    static var allTests: [(String, (TestNSEnergyFormatter) -> () throws -> Void)] {
+        return [
+            ("test_stringFromJoulesJoulesRegion", test_stringFromJoulesJoulesRegion),
+            ("test_stringFromJoulesCaloriesRegion", test_stringFromJoulesCaloriesRegion),
+            ("test_stringFromJoulesCaloriesRegionFoodEnergyUse", test_stringFromJoulesCaloriesRegionFoodEnergyUse),
+            ("test_stringFromValue", test_stringFromValue),
+            ("test_unitStringFromValue", test_unitStringFromValue),
+            ("test_unitStringFromJoules", test_unitStringFromJoules)
+        ]
+    }
+    
+    override func setUp() {
+        formatter.numberFormatter.locale = Locale(identifier: "en_US")
+        formatter.isForFoodEnergyUse = false
+        super.setUp()
+    }
+
+    func test_stringFromJoulesJoulesRegion() {
+        formatter.numberFormatter.locale = Locale(identifier: "de_DE")
+        XCTAssertEqual(formatter.string(fromJoules: -100000), "-100 kJ")
+        XCTAssertEqual(formatter.string(fromJoules: -1), "-0,001 kJ")
+        XCTAssertEqual(formatter.string(fromJoules: 100000000), "100.000 kJ")
+    }
+    
+    
+    func test_stringFromJoulesCaloriesRegion() {
+        XCTAssertEqual(formatter.string(fromJoules: -10000), "-2.39 kcal")
+        XCTAssertEqual(formatter.string(fromJoules: 0.00001), "0 cal")
+        XCTAssertEqual(formatter.string(fromJoules: 0.0001), "0 cal")
+        XCTAssertEqual(formatter.string(fromJoules: 1), "0.239 cal")
+        XCTAssertEqual(formatter.string(fromJoules: 10000), "2.39 kcal")
+    }
+    
+    func test_stringFromJoulesCaloriesRegionFoodEnergyUse() {
+        formatter.isForFoodEnergyUse = true
+        XCTAssertEqual(formatter.string(fromJoules: -1), "-0 Cal")
+        XCTAssertEqual(formatter.string(fromJoules: 0.001), "0 cal")
+        XCTAssertEqual(formatter.string(fromJoules: 0.1), "0.024 cal")
+        XCTAssertEqual(formatter.string(fromJoules: 1), "0.239 cal")
+        XCTAssertEqual(formatter.string(fromJoules: 10000), "2.39 Cal")
+    }
+    
+    func test_stringFromValue() {
+        formatter.unitStyle = Formatter.UnitStyle.long
+        XCTAssertEqual(formatter.string(fromValue: 0.002, unit: EnergyFormatter.Unit.kilojoule),"0.002 kilojoules")
+        XCTAssertEqual(formatter.string(fromValue:0, unit:EnergyFormatter.Unit.joule), "0 joules")
+        XCTAssertEqual(formatter.string(fromValue:1, unit:EnergyFormatter.Unit.joule), "1 joule")
+        
+        formatter.unitStyle = Formatter.UnitStyle.short
+        XCTAssertEqual(formatter.string(fromValue: 0.00000001, unit:EnergyFormatter.Unit.kilocalorie), "0kcal")
+        XCTAssertEqual(formatter.string(fromValue: 2.4, unit: EnergyFormatter.Unit.calorie), "2.4cal")
+        XCTAssertEqual(formatter.string(fromValue: 123456, unit: EnergyFormatter.Unit.calorie), "123,456cal")
+        
+        formatter.unitStyle = Formatter.UnitStyle.medium
+        formatter.isForFoodEnergyUse = true
+        XCTAssertEqual(formatter.string(fromValue: 0.00000001, unit: EnergyFormatter.Unit.calorie), "0 cal")
+        XCTAssertEqual(formatter.string(fromValue: 987654321, unit: EnergyFormatter.Unit.kilocalorie), "987,654,321 Cal")
+        
+        formatter.isForFoodEnergyUse = false
+        XCTAssertEqual(formatter.string(fromValue: 5.3, unit: EnergyFormatter.Unit.kilocalorie), "5.3 kcal")
+        XCTAssertEqual(formatter.string(fromValue: 873.2345, unit: EnergyFormatter.Unit.calorie), "873.234 cal")
+    }
+    
+    func test_unitStringFromJoules() {
+        var unit = EnergyFormatter.Unit.joule
+        XCTAssertEqual(formatter.unitString(fromJoules: -100000, usedUnit: &unit), "kcal")
+        XCTAssertEqual(unit, EnergyFormatter.Unit.kilocalorie)
+        
+        XCTAssertEqual(formatter.unitString(fromJoules: 0, usedUnit: &unit), "kcal")
+        XCTAssertEqual(unit, EnergyFormatter.Unit.kilocalorie)
+        
+        XCTAssertEqual(formatter.unitString(fromJoules: 0.0001, usedUnit: &unit), "cal")
+        XCTAssertEqual(unit, EnergyFormatter.Unit.calorie)
+        
+        XCTAssertEqual(formatter.unitString(fromJoules: 4184, usedUnit: &unit), "cal")
+        XCTAssertEqual(unit, EnergyFormatter.Unit.calorie)
+        
+        XCTAssertEqual(formatter.unitString(fromJoules: 4185, usedUnit: &unit), "kcal")
+        XCTAssertEqual(unit, EnergyFormatter.Unit.kilocalorie)
+        
+        XCTAssertEqual(formatter.unitString(fromJoules: 100000, usedUnit: &unit), "kcal")
+        XCTAssertEqual(unit, EnergyFormatter.Unit.kilocalorie)
+        
+        formatter.numberFormatter.locale = Locale(identifier: "de_DE")
+        XCTAssertEqual(formatter.unitString(fromJoules: -100000, usedUnit: &unit), "kJ")
+        XCTAssertEqual(unit, EnergyFormatter.Unit.kilojoule)
+        
+        XCTAssertEqual(formatter.unitString(fromJoules: 0, usedUnit: &unit), "kJ")
+        XCTAssertEqual(unit, EnergyFormatter.Unit.kilojoule)
+        
+        XCTAssertEqual(formatter.unitString(fromJoules: 0.0001, usedUnit: &unit), "J")
+        XCTAssertEqual(unit, EnergyFormatter.Unit.joule)
+        
+        XCTAssertEqual(formatter.unitString(fromJoules: 1000, usedUnit: &unit), "J")
+        XCTAssertEqual(unit, EnergyFormatter.Unit.joule)
+        
+        XCTAssertEqual(formatter.unitString(fromJoules: 1000.01, usedUnit: &unit), "kJ")
+        XCTAssertEqual(unit, EnergyFormatter.Unit.kilojoule)
+    }
+    
+    func test_unitStringFromValue() {
+        formatter.isForFoodEnergyUse = true
+        formatter.unitStyle = Formatter.UnitStyle.long
+        XCTAssertEqual(formatter.unitString(fromValue: 1, unit: EnergyFormatter.Unit.kilocalorie), "Calories")
+        XCTAssertEqual(formatter.unitString(fromValue: 2, unit: EnergyFormatter.Unit.kilocalorie), "Calories")
+        
+        formatter.unitStyle = Formatter.UnitStyle.medium
+        XCTAssertEqual(formatter.unitString(fromValue: 0.00000001, unit: EnergyFormatter.Unit.kilocalorie), "Cal")
+        XCTAssertEqual(formatter.unitString(fromValue: 987654321, unit: EnergyFormatter.Unit.kilocalorie), "Cal")
+        
+        formatter.unitStyle = Formatter.UnitStyle.short
+        XCTAssertEqual(formatter.unitString(fromValue: 0.00000001, unit: EnergyFormatter.Unit.calorie), "cal")
+        XCTAssertEqual(formatter.unitString(fromValue: 123456, unit: EnergyFormatter.Unit.kilocalorie), "C")
+        
+        formatter.isForFoodEnergyUse = false
+        formatter.unitStyle = Formatter.UnitStyle.long
+        XCTAssertEqual(formatter.unitString(fromValue: 0.002, unit: EnergyFormatter.Unit.kilojoule), "kilojoules")
+        
+        formatter.unitStyle = Formatter.UnitStyle.medium
+        XCTAssertEqual(formatter.unitString(fromValue: 0.00000001, unit: EnergyFormatter.Unit.kilocalorie), "kcal")
+        XCTAssertEqual(formatter.unitString(fromValue: 987654321, unit: EnergyFormatter.Unit.kilocalorie), "kcal")
+        
+        formatter.unitStyle = Formatter.UnitStyle.short
+        XCTAssertEqual(formatter.unitString(fromValue: 0.00000001, unit: EnergyFormatter.Unit.calorie), "cal")
+        XCTAssertEqual(formatter.unitString(fromValue: 123456, unit: EnergyFormatter.Unit.joule), "J")
+    }
+
+}
diff --git a/TestFoundation/TestNSNumber.swift b/TestFoundation/TestNSNumber.swift
index e37c3c8..20015b9 100644
--- a/TestFoundation/TestNSNumber.swift
+++ b/TestFoundation/TestNSNumber.swift
@@ -77,8 +77,8 @@
         XCTAssertEqual(NSNumber(value: Int8(0)).uint64Value, UInt64(0))
         XCTAssertEqual(NSNumber(value: Int8(-37)).boolValue, true)
         XCTAssertEqual(NSNumber(value: Int8(-37)).int8Value, Int8(-37))
-#if !(os(Linux) && arch(arm))
-        // Linux/arm chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
+#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
+        // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
         XCTAssertEqual(NSNumber(value: Int8(-37)).int16Value, Int16(-37))
         XCTAssertEqual(NSNumber(value: Int8(-37)).int32Value, Int32(-37))
         XCTAssertEqual(NSNumber(value: Int8(-37)).int64Value, Int64(-37))
@@ -103,32 +103,32 @@
         XCTAssertEqual(NSNumber(value: Int8.max).uint64Value, UInt64(Int8.max))
         XCTAssertEqual(NSNumber(value: Int8.min).boolValue, true)
         XCTAssertEqual(NSNumber(value: Int8.min).int8Value, Int8(Int8.min))
-#if !(os(Linux) && arch(arm))
-        // Linux/arm chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
+#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
+        // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
         XCTAssertEqual(NSNumber(value: Int8.min).int16Value, Int16(Int8.min))
         XCTAssertEqual(NSNumber(value: Int8.min).int32Value, Int32(Int8.min))
         XCTAssertEqual(NSNumber(value: Int8.min).int64Value, Int64(Int8.min))
 #endif
         XCTAssertEqual(NSNumber(value: Int8(0)).floatValue, Float(0))
-#if !(os(Linux) && arch(arm))
-        // Linux/arm chars are unsigned, so Int8 in Swift, until this issue is resolved, this test will always fail.
+#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
+        // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
         XCTAssertEqual(NSNumber(value: Int8(-37)).floatValue, Float(-37))
 #endif
         XCTAssertEqual(NSNumber(value: Int8(42)).floatValue, Float(42))
         XCTAssertEqual(NSNumber(value: Int8.max).floatValue, Float(Int8.max))
-#if !(os(Linux) && arch(arm))
-        // Linux/arm chars are unsigned, so Int8 in Swift, until this issue is resolved, this test will always fail.
+#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
+        // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
         XCTAssertEqual(NSNumber(value: Int8.min).floatValue, Float(Int8.min))
 #endif
         XCTAssertEqual(NSNumber(value: Int8(0)).doubleValue, Double(0))
-#if !(os(Linux) && arch(arm))
-        // Linux/arm chars are unsigned, so Int8 in Swift, until this issue is resolved, this test will always fail.
+#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
+        // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
         XCTAssertEqual(NSNumber(value: Int8(-37)).doubleValue, Double(-37))
 #endif
         XCTAssertEqual(NSNumber(value: Int8(42)).doubleValue, Double(42))
         XCTAssertEqual(NSNumber(value: Int8.max).doubleValue, Double(Int8.max))
-#if !(os(Linux) && arch(arm))
-        // Linux/arm chars are unsigned, so Int8 in Swift, until this issue is resolved, this test will always fail.
+#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
+        // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
         XCTAssertEqual(NSNumber(value: Int8.min).doubleValue, Double(Int8.min))
 #endif
     }
@@ -279,8 +279,8 @@
         XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: true)), ComparisonResult.orderedAscending)
 
         XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Int8(0))), ComparisonResult.orderedSame)
-#if !(os(Linux) && arch(arm))
-        // Linux/arm chars are unsigned, so Int8 in Swift, until this issue is resolved, this test will always fail.
+#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
+        // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
         XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Int8(-1))), ComparisonResult.orderedDescending)
 #endif
         XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Int8(1))), ComparisonResult.orderedAscending)
@@ -301,28 +301,28 @@
     func test_compareNumberWithChar() {
         XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: Int8(42))), ComparisonResult.orderedSame)
         XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: Int8(0))), ComparisonResult.orderedDescending)
-#if !(os(Linux) && arch(arm))
-        // Linux/arm chars are unsigned, so Int8 in Swift, until this issue is resolved, this test will always fail.
+#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
+        // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
         XCTAssertEqual(NSNumber(value: Int8(-37)).compare(NSNumber(value: Int8(16))), ComparisonResult.orderedAscending)
 #endif
 
         XCTAssertEqual(NSNumber(value: Int8(1)).compare(NSNumber(value: true)), ComparisonResult.orderedSame)
         XCTAssertEqual(NSNumber(value: Int8(1)).compare(NSNumber(value: false)), ComparisonResult.orderedDescending)
-#if !(os(Linux) && arch(arm))
-        // Linux/arm chars are unsigned, so Int8 in Swift, until this issue is resolved, this test will always fail.
+#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
+        // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
         XCTAssertEqual(NSNumber(value: Int8(-37)).compare(NSNumber(value: true)), ComparisonResult.orderedAscending)
 #endif
 
         XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: UInt8(42))), ComparisonResult.orderedSame)
         XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: UInt8(16))), ComparisonResult.orderedDescending)
-#if !(os(Linux) && arch(arm))
-        // Linux/arm chars are unsigned, so Int8 in Swift, until this issue is resolved, this test will always fail.
+#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
+        // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
         XCTAssertEqual(NSNumber(value: Int8(-37)).compare(NSNumber(value: UInt8(255))), ComparisonResult.orderedAscending)
 #endif
 
         XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: Float(42))), ComparisonResult.orderedSame)
-#if !(os(Linux) && arch(arm))
-        // Linux/arm chars are unsigned, so Int8 in Swift, until this issue is resolved, this test will always fail.
+#if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le)))
+        // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail.
         XCTAssertEqual(NSNumber(value: Int8(-16)).compare(NSNumber(value: Float(-37.5))), ComparisonResult.orderedDescending)
 #endif
         XCTAssertEqual(NSNumber(value: Int8(16)).compare(NSNumber(value: Float(16.1))), ComparisonResult.orderedAscending)
diff --git a/TestFoundation/TestNSString.swift b/TestFoundation/TestNSString.swift
index 34bd07b..98e33d5 100644
--- a/TestFoundation/TestNSString.swift
+++ b/TestFoundation/TestNSString.swift
@@ -1094,7 +1094,13 @@
     ComparisonTest("t", "tt"),
     ComparisonTest("t", "Tt"),
     ComparisonTest("\u{0}", "",
-        reason: "https://bugs.swift.org/browse/SR-332"),
+        reason: {
+#if _runtime(_ObjC)
+    return ""
+#else
+    return "https://bugs.swift.org/browse/SR-332"
+#endif
+    }()),
     ComparisonTest("\u{0}", "\u{0}",
         reason: "https://bugs.swift.org/browse/SR-332"),
     ComparisonTest("\r\n", "t"),
diff --git a/TestFoundation/TestNSTextCheckingResult.swift b/TestFoundation/TestNSTextCheckingResult.swift
index 7eabe4a..c74fa09 100644
--- a/TestFoundation/TestNSTextCheckingResult.swift
+++ b/TestFoundation/TestNSTextCheckingResult.swift
@@ -32,7 +32,7 @@
            let searchString = "1x030cy"
            let searchOptions: NSMatchingOptions = []
            let searchRange = NSMakeRange(0,7)
-           let match: TextCheckingResult =  regex.firstMatch(in: searchString, options: searchOptions, range: searchRange)!
+           let match: NSTextCheckingResult =  regex.firstMatch(in: searchString, options: searchOptions, range: searchRange)!
            //Positive offset
            var result = match.resultByAdjustingRangesWithOffset(1)
            XCTAssertEqual(result.range(at: 0).location, 6)
diff --git a/TestFoundation/TestNSURLSession.swift b/TestFoundation/TestNSURLSession.swift
index d86e749..cce1508 100644
--- a/TestFoundation/TestNSURLSession.swift
+++ b/TestFoundation/TestNSURLSession.swift
@@ -32,6 +32,7 @@
             ("test_finishTaskAndInvalidate", test_finishTasksAndInvalidate),
             ("test_taskError", test_taskError),
             ("test_taskCopy", test_taskCopy),
+            ("test_cancelTask", test_cancelTask),
         ]
     }
 
@@ -297,6 +298,26 @@
         
         XCTAssert(task.isEqual(task.copy()))
     }
+
+    func test_cancelTask() {
+        let serverReady = ServerSemaphore()
+        globalDispatchQueue.async {
+            do {
+                try self.runServer(with: serverReady)
+            } catch {
+                XCTAssertTrue(true)
+                return
+            }
+        }
+        serverReady.wait()
+        let url = URL(string: "http://127.0.0.1:\(serverPort)/Peru")!
+        let d = DataTask(with: expectation(description: "Task to be canceled"))
+        d.cancelExpectation = expectation(description: "URLSessionTask wasn't canceled")
+        d.run(with: url)
+        d.cancel()
+        waitForExpectations(timeout: 12)
+    }
+
 }
 
 class SessionDelegate: NSObject, URLSessionDelegate {
@@ -314,6 +335,8 @@
     var capital = "unknown"
     var session: URLSession! = nil
     var task: URLSessionDataTask! = nil
+    var cancelExpectation: XCTestExpectation?
+
     public var error = false
 
     init(with expectation: XCTestExpectation) {
@@ -335,20 +358,26 @@
         task = session.dataTask(with: url)
         task.resume()
     }
+
+    func cancel() {
+        task.cancel()
+    }
 }
 
 extension DataTask : URLSessionDataDelegate {
-     public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
-         capital = String(data: data, encoding: String.Encoding.utf8)!
-         dataTaskExpectation.fulfill()
-     }
+    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
+        capital = String(data: data, encoding: String.Encoding.utf8)!
+        dataTaskExpectation.fulfill()
+    }
 }
 
 extension DataTask : URLSessionTaskDelegate {
     public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
          guard let e = error as? URLError else { return }
-         XCTAssertEqual(e.code, .timedOut, "Unexpected error code")
          dataTaskExpectation.fulfill()
+         if let cancellation = cancelExpectation {
+             cancellation.fulfill()
+         }
          self.error = true
      }
 } 
diff --git a/TestFoundation/main.swift b/TestFoundation/main.swift
index b407103..849ce33 100644
--- a/TestFoundation/main.swift
+++ b/TestFoundation/main.swift
@@ -35,6 +35,7 @@
     testCase(TestNSDecimal.allTests),
     testCase(TestNSDictionary.allTests),
     testCase(TestNSError.allTests),
+    testCase(TestNSEnergyFormatter.allTests),
     testCase(TestNSFileManager.allTests),
     testCase(TestNSGeometry.allTests),
     testCase(TestNSHTTPCookie.allTests),