Nerd For Tech
Published in

Nerd For Tech

Meet Strings in Swift as iOS Developer

Photo by Mika Baumeister on Unsplash

Strings in swift are very commonly used by iOS Developers. We solve variety of problems in our development with the power of strings. But we generally overlook some of important functions in strings. In this article I try to collect such functions and add some extensions possibly.

Separate substrings from string

In development we come across reading csv files and separating tags entered by user. In these scenarios we need to create an array of strings from a string separated by some separator. ‘components’ function in swift can be used here.

let res = str.components(separatedBy: ",")

output is array of strings which are separated by ‘,’ in original string.

Index based use cases

characters in a string can be accessed by index of string. unlike other programming languages, we won't be using integer based accessing in swift.

One prominent reason for this is length of characters in swift is not uniform.Combination of unicode points to make up character varies. so indexes are calculated with respect to string every time.

Index … After

sometimes we need to get the index of character after certain part/index of string i.e., index of ‘e’ in ‘elephant’ starting from 2nd character(‘lephant’). Below is the extension that can help you.

extension Array where Element == Character {  func index(of character: Character, after index: Int) -> Int? {    for i in index..<self.count where self[i] == character {       return i    }    return nil  }}

Partial Replacement

Consider you are making an IDE or some editor where user is provided to replace the part of string with another. We can use following to do so.

str.replacingOccurrences(of: "xcode", with: "Xcode")

Also if we want to replace the string between two given characters or sub strings, we can use following.

guard let startIndex = str.firstIndex(of: "a") else { return false}
guard let endIndex = str.firstIndex(of: "o") else { return false}
str.replaceSubrange(startIndex...endIndex, with: "oil")

Boundary Testing

Test if substring is present in a string from starting or ending.

From starting

str.hasPrefix("i")// testing that a string is lexicographically greater than otherstr.lexicographicallyPrecedes("zzz")

From ending


Difference between two strings

As a developer we might come across a question how many changes(insertions and removals) need to be done on a str1 to become str2.

str = "oil"let dif = str.difference(from: "oii")print(dif) /* CollectionDifference<Character>(insertions: [Swift.CollectionDifference<Swift.Character>.Change.insert(offset: 2, element: "l", associatedWith: nil)], removals: [Swift.CollectionDifference<Swift.Character>.Change.remove(offset: 2, element: "i", associatedWith: nil)]) */print(dif.insertions.count+dif.removals.count) // 2


It is not that complex to find highest character in a string. But there is some ambiguity around max() in strings. Following helps to clear that

str = "aAB"str.max() // a

Be aware that small letters are considered maximum.

Count of Decimals/lower case letters/ upper case letters/….(CharacterSet)

As title says having count of only letters or only decimals or lower case or even more from alpha numeric strings can be helpful. Below is small extension to do so.

extension String {  func count(of characterSet: CharacterSet) -> Int {    var count = 0    var range = self.rangeOfCharacter(from: characterSet)    while range != nil {      count = count + 1      guard let ub = range?.upperBound else {         break      }      range = self[ub...].rangeOfCharacter(from: characterSet)    }    return count   }} 

That’s it…

Thanks for reading…



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sai Durga Mahesh

Sai Durga Mahesh


Using Data Science to provide better solutions to real word problems