Better String in Swift Using Stryng

20th December 2017

If you write in Swift, then there’s a good chance you’ve tried to access a section (Substring) of a String.

Usually it’s done by using an index, and an offset. But in some cases you need to specify the start index along with an offset, and also an end index with an offset.

It gets a bit messy.

Luckily I’ve just discovered Stryng on GitHub, and it’s a beautiful solution.

There’s a ton of examples, and you should totally read the README even if you aren’t going to use it. But here’s my favourite:

Before Stryng:

let message = “One Two Three”
message[message.index(message.startIndex, offsetBy: 4)..<message.index(message.startIndex, offsetBy: 7)] // “Two”

After Stryng:

let message = “One Two Three”
message[4..<7] // "Two”


Found this post useful? Why not buy me a coffee? Alternatively, I'd like to point you towards Ecologi, where you can subscribe to a plan where you fund various climate positive projects, the planting of trees, and other carbon reduction projects.