Skip to content

Instantly share code, notes, and snippets.

@erdemildiz
Forked from foxicode/String+subscript.swift
Last active September 26, 2020 16:12
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 erdemildiz/a77d498d6e340758cd58cfb1d3d6d727 to your computer and use it in GitHub Desktop.
Save erdemildiz/a77d498d6e340758cd58cfb1d3d6d727 to your computer and use it in GitHub Desktop.
Swift String subscript extension
#https://medium.com/better-programming/24-swift-extensions-for-cleaner-code-41e250c9c4c3
import Foundation
extension String {
subscript (i: Int) -> Character {
return self[index(startIndex, offsetBy: i)]
}
subscript (bounds: CountableRange<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
if end < start { return "" }
return self[start..<end]
}
subscript (bounds: CountableClosedRange<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
if end < start { return "" }
return self[start...end]
}
subscript (bounds: CountablePartialRangeFrom<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(endIndex, offsetBy: -1)
if end < start { return "" }
return self[start...end]
}
subscript (bounds: PartialRangeThrough<Int>) -> Substring {
let end = index(startIndex, offsetBy: bounds.upperBound)
if end < startIndex { return "" }
return self[startIndex...end]
}
subscript (bounds: PartialRangeUpTo<Int>) -> Substring {
let end = index(startIndex, offsetBy: bounds.upperBound)
if end < startIndex { return "" }
return self[startIndex..<end]
}
}
@erdemildiz
Copy link
Author

Usage

let subscript1 = "Hello, world!"[7...]
let subscript2 = "Hello, world!"[7...11] 

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