Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Created December 11, 2019 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/294f74a00c122d1c0c3a148a337ea895 to your computer and use it in GitHub Desktop.
Save robertmryan/294f74a00c122d1c0c3a148a337ea895 to your computer and use it in GitHub Desktop.
Extension to `String` to allow numeric indexes for ranges
extension String {
public subscript(range: Range<String.IndexDistance>) -> Substring {
let lowerBound = index(startIndex, offsetBy: range.lowerBound)
let upperBound = index(startIndex, offsetBy: range.upperBound)
return self[lowerBound..<upperBound]
}
public subscript(range: ClosedRange<String.IndexDistance>) -> Substring {
let lowerBound = index(startIndex, offsetBy: range.lowerBound)
let upperBound = index(startIndex, offsetBy: range.upperBound)
return self[lowerBound...upperBound]
}
public subscript(range: PartialRangeFrom<String.IndexDistance>) -> Substring {
let lowerBound = index(startIndex, offsetBy: range.lowerBound)
return self[lowerBound...]
}
public subscript(range: PartialRangeThrough<String.IndexDistance>) -> Substring {
let upperBound = index(startIndex, offsetBy: range.upperBound)
return self[...upperBound]
}
public subscript(range: PartialRangeUpTo<String.IndexDistance>) -> Substring {
let upperBound = index(startIndex, offsetBy: range.upperBound)
return self[..<upperBound]
}
}
@robertmryan
Copy link
Author

Thus:

let string = "Hello, World"
let result = string[3...4]
print(result)

Resulting in

lo

Obviously, result is still Substring, so you you really needed a String, you’d create one:

func foo(_ string: String) { ... }

foo(String(result))

Or modify your function to accept any StringProtocol:

func foo<S: StringProtocol>(_ string: S) { ... }

foo(result)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment