A Better Way To Access String Methods In Swift

Anybody who has worked with Strings in Swift has faced this – you can’t use integer indices to access characters in the String. Why? Because according to Official Swift Guide from Apple, every Character instance in Swift is an Extended Grapheme Cluster (read more @ https://goo.gl/xUsMv9 ). Long story short – it’s due to handling Unicode character set. So, how do you get a better way? (Better from the perspective that you have to write less code)

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

  1. var greetings: String = "Hello world"  
  2. 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! }
  1. extension String {  
  2.     func at(indexSpecified: Int) -> Character {  
  3.         let offset = indexSpecified  
  4.         let c = self[ self.index( self.startIndex, offsetBy:offset ) ]  
  5.   
  6.         return c  
  7.     }  
  8. }  
Testing Time
  1. var greetings: String = "Hello world"  
  2. var c = greetings.at(indexSpecified: 8)  
And we have our a little bit  of tidied up code that looks familiar and breaks less sweat. Now this may not be the best way, and some people may like the vanilla way but it’s always nice to do things with less code isn’t it? 
Ebook Download
View all
Learn
View all