Loop String Characters With Index In Swift 4.0

Nikhil Patil
1 min readOct 3, 2017

--

Let’s say you want to print each character of a string using the index value inside a for-loop, a very simple way of doing this is :-

let name = "nick" // The String which we want to print.// 0..< will give a range of numbers from 0 to (string.length - 1)for i in 0..<name.count {    // Operation name[i] is not allowed in Swift, an alternative is    let index = name.index[name.startIndex, offsetBy: i]
print(name[index])
}

The reason name[i] is not allowed because each character require different amount to memory to store thus in order to determine which Character is at a particular position, you have start reading from the start of each String and move forward(offset) by 1 as shown in code :-

// Start from start-index and iterate forward by 1
let index = name.index[name.startIndex, offsetBy: i]

--

--

Nikhil Patil

Interested in data science, software architecture, technology and likes to write about it.