Skip to content

Commit

Permalink
Swift string support
Browse files Browse the repository at this point in the history
  • Loading branch information
mattmassicotte committed Apr 30, 2022
1 parent 3f0d413 commit ca31b92
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ func apply(_ change: RangeMutation) -> NSRange?
// creating
init(_ textRange: NSTextRange, provider: NSTextElementProvider)
init?(_ textRange: UITextRange, textView: UITextView)

// working with Swift String
func range(in string: String) -> Range<String.Index>?
```

**NSTextRange**
Expand Down Expand Up @@ -76,6 +79,13 @@ func intersects(integersIn range: NSRange) -> Bool
var limitSpanningRange: NSRange?
```

**String**

```Swift
subscript(range: Range<Int>) -> Substring?
subscript(range: NSRange) -> Substring?
```

### Suggestions or Feedback

We'd love to hear from you! Get in touch via [twitter](https://twitter.com/chimehq), an issue, or a pull request.
Expand Down
24 changes: 24 additions & 0 deletions Sources/Rearrange/String+NSRange.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import Foundation

public extension NSRange {
func range(in string: String) -> Range<String.Index>? {
return Range<String.Index>(self, in: string)
}
}

public extension String {
subscript(range: Range<Int>) -> Substring? {
get {
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.count)

return self[start..<end]
}
}

subscript(range: NSRange) -> Substring? {
get {
return range.range(in: self).flatMap({ self[$0] })
}
}
}

0 comments on commit ca31b92

Please sign in to comment.