hsleedevelop
9/13/2014 - 5:11 PM

A better Swift NSRange

A better Swift NSRange

// Playground - noun: a place where people can play

import Cocoa

extension NSRange {

    init(location:Int, length:Int) {
        self.location = location
        self.length = length
    }

    init(_ location:Int, _ length:Int) {
        self.location = location
        self.length = length
    }

    init(range:Range <Int>) {
        self.location = range.startIndex
        self.length = range.endIndex - range.startIndex
    }

    init(_ range:Range <Int>) {
        self.location = range.startIndex
        self.length = range.endIndex - range.startIndex
    }

    var startIndex:Int { get { return location } }
    var endIndex:Int { get { return location + length } }
    var asRange:Range<Int> { get { return location..<location + length } }
    var isEmpty:Bool { get { return length == 0 } }

    func contains(index:Int) -> Bool {
        return index >= location && index < endIndex
    }
    
    func clamp(index:Int) -> Int {
        return max(self.startIndex, min(self.endIndex - 1, index))
    }
    
    func intersects(range:NSRange) -> Bool {
        return NSIntersectionRange(self, range).isEmpty == false
    }

    func intersection(range:NSRange) -> NSRange {
        return NSIntersectionRange(self, range)        
    }
    
    func union(range:NSRange) -> NSRange {
        return NSUnionRange(self, range)
    }
    
}

NSRange(0, 10).clamp(10)
NSRange(0, 10).contains(10)