Skip to content

Instantly share code, notes, and snippets.

@HamGuy
Last active August 29, 2015 14:11
Show Gist options
  • Save HamGuy/ccbc8c6a4e475fb68883 to your computer and use it in GitHub Desktop.
Save HamGuy/ccbc8c6a4e475fb68883 to your computer and use it in GitHub Desktop.
// 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment