The simple and easy way is to convert String to Array to get the benefit of the index just like that:
let input = Array(str)
If you try to index into String without using any conversion.
Here is the full code of the extension:
extension String {
subscript (_ index: Int) -> String {
get {
String(self[self.index(startIndex, offsetBy: index)])
}
set {
if index >= count {
insert(Character(newValue), at: self.index(self.startIndex, offsetBy: count))
} else {
insert(Character(newValue), at: self.index(self.startIndex, offsetBy: index))
}
}
}
}
Now that you can read and write a single character from string using its index just like you originally wanted to:
var str = "car"
str[3] = "d"
print(str)
It’s simple and useful way to use it and get through Swift’s String access model.
Now that you’ll feel it’s smooth sailing next time when you can loop through the string just as it is, not casting it into Array.
Try it out, and see if it can help!
stringts.insert("(", atIndex: 0)