What you need to do now – vanilla Swift code
Okay let’s say you have a String with value “Hello World” and you want to get the character in the 8th index. What you need to do is this
- var greetings: String = "Hello world"
- greetings[ greetings.index( greetings.startIndex, offsetBy: 8 ) ]
If you’re coming from languages like C++/Java/C# you may say – damn! I can do that like greetings[8] or greetings.at(8) for C++ and done! [ Yeah I wish it was that easy! ]
So let’s get a better way, how we can get something similiar to C++/Java/C# at least!
Typical OOP approach – Extend String with a user defined class – Fails
String is a Struct type in Swift. So no OOP. No party either. However you can extend it and add new methods. That’s what we’re going to do, add a new method called at(indexSpecifeld : Int) that returns the character at indexSpecified.
at(indexSpecified : Int) -> Character { // This method works! }- extension String {
- func at(indexSpecified: Int) -> Character {
- let offset = indexSpecified
- let c = self[ self.index( self.startIndex, offsetBy:offset ) ]
- return c
- }
- }
- var greetings: String = "Hello world"
- var c = greetings.at(indexSpecified: 8)


Join the conversation! Your thoughts help the community grow.