Merge pull request #878 from naithar/guard-in-equal

diff --git a/Docs/Status.md b/Docs/Status.md
index 071a49c..7a27e3c 100644
--- a/Docs/Status.md
+++ b/Docs/Status.md
@@ -198,7 +198,7 @@
     |-----------------------------|-----------------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|
     | `RegularExpression`         | Mostly Complete | Substantial   | `NSCoding` remains unimplemented                                                                                                                                 |
     | `Scanner`                   | Mostly Complete | Incomplete    | `scanHex<T: _FloatLike>(_:locale:locationToScanFrom:to:)` and `localizedScannerWithString(_:)` remain unimplemented                                              |
-    | `TextCheckingResult`        | Mostly Complete | Incomplete    | `NSCoding`, `NSCopying`, `resultType`, and `range(at:)` remain unimplemented                                                                                     |
+    | `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/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/NSCalendar.swift b/Foundation/NSCalendar.swift
index 9b97ccc..e3b427f 100644
--- a/Foundation/NSCalendar.swift
+++ b/Foundation/NSCalendar.swift
@@ -1263,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?
diff --git a/Foundation/NSDictionary.swift b/Foundation/NSDictionary.swift
index 02cdc7b..defa889 100644
--- a/Foundation/NSDictionary.swift
+++ b/Foundation/NSDictionary.swift
@@ -138,7 +138,7 @@
     }
     
     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 {
@@ -158,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()
@@ -171,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/NSOrderedSet.swift b/Foundation/NSOrderedSet.swift
index 69712d3..33b5f4e 100644
--- a/Foundation/NSOrderedSet.swift
+++ b/Foundation/NSOrderedSet.swift
@@ -292,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]) {
@@ -328,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/NSRegularExpression.swift b/Foundation/NSRegularExpression.swift
index 5bc263d..fca86c1 100644
--- a/Foundation/NSRegularExpression.swift
+++ b/Foundation/NSRegularExpression.swift
@@ -113,8 +113,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
     }
@@ -133,7 +133,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)
@@ -151,7 +151,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)
@@ -163,9 +163,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)
             }
@@ -182,9 +182,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
         }
@@ -193,7 +193,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 {
@@ -264,7 +264,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 e552ae1..fdd5b99 100644
--- a/Foundation/NSSet.swift
+++ b/Foundation/NSSet.swift
@@ -152,7 +152,7 @@
                 }
             })
         } else {
-            self.init(array: set.map { $0 })
+            self.init(array: Array(set))
         }
     }
 }
@@ -423,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/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/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/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)