Skip to content

Instantly share code, notes, and snippets.

@lokshunhung
Last active July 21, 2023 03:52
Show Gist options
  • Save lokshunhung/ccd3909513b03c98beff71b4a0b91da9 to your computer and use it in GitHub Desktop.
Save lokshunhung/ccd3909513b03c98beff71b4a0b91da9 to your computer and use it in GitHub Desktop.
StringInd.swift
public struct Ind {
private let s: String
public let index: String.Index
public init(_ s: String, _ index: String.Index) {
self.s = s
self.index = index
}
public init(_ s: String, _ f: (String) -> String.Index) {
self.init(s, f(s))
}
public var start: Self { .init(s, s.startIndex) }
public var end: Self { .init(s, s.endIndex) }
public var prev: Self { .init(s, s.index(before: index)) }
public var next: Self { .init(s, s.index(after: index)) }
public func offset(by distance: Int) -> Self {
.init(s, s.index(index, offsetBy: distance))
}
public func offset(by distance: Int, limitedBy limit: String.Index) -> Self? {
s.index(index, offsetBy: distance, limitedBy: limit)
.map { .init(s, $0) }
}
public func offset(by distance: Int, limit f: (String) -> String.Index) -> Self? {
offset(by: distance, limitedBy: f(s))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment