Substring is a tiny library allows you to substring without boilerplate, verbose and complex code.
The strings management of Swift
is one of the most painful feature ever:
let string = "Substring API sucks!"
let start = string.index(string.startIndex, offsetBy: 1)
let end = string.index(string.startIndex, offsetBy: 6)
let substring = String(string[start..<end])
No! Stop it!
Now with this tiny library called Substring
, you can simplly do this:
let substring = string[1..<6].string
Or this, if you prefer:
let substring = string.substring(in: 1..<6).string
Learn more.
Type | Requirement | |
---|---|---|
Platform |
iOS |
8.0+ |
macOS |
10.9 |
|
tvOS |
9.0 |
|
watchOS |
2.0 |
|
Linux |
✔ |
|
IDE |
Xcode |
10.2+ |
Language |
Swift |
5+ |
Substring
is open-sourced software, licensed under the MIT
license.
import Substring
let string = "A_Example_String"
// STR: A _ E x a m p l e _ S t r i n g
// IDX: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
print(string.substring(at: 1).string, string[1].string) // "_"
print(string.substring(to: 4).string, string[...4].string) // "A_Exa"
print(string.substring(from: 2).string, string[2...].string) // "Example_String"
print(string.substring(before: 5).string, string[..<5].string) // "A_Exa"
print(string.substring(in: 2...5).string, string[2...5].string) // "Exam"
print(string.substring(in: 2..<5).string, string[2..<5].string) // "Exa"
// ...