var str: String = "sometext"
for i in str.characters.indices
{
str[i] = "c"
}
print(str)
I'm getting the following error:
error: cannot assign through subscript: subscript is get-only
You are getting this error because the subscript method of a Swift String is get-only like it is saying in your warning. This is different from an Array.
Array:
array[0] ✅
array[0] = 0 ✅
String:
str[0] ❌
str[0] = "0" ❌
str[str.startIndex.advancedBy(0)] ✅
Use replaceRange for accomplishing your task.
Example:
var value = "green red blue"
value.replaceRange(value.startIndex.advancedBy(
6)..<value.startIndex.advancedBy(6 + 3),
with: "yellow")
print(value)
Result:
green yellow blue
Also have a look at this superb blog article from Ole Begemann who explains how Swift Strings work very detailed. You will also find the answer why you can't use subscript methods on Swift Strings.
Because of the way Swift strings are stored, the String type does not support random access to its Characters via an integer index — there is no direct equivalent to NSStringʼs characterAtIndex: method. Conceptually, a String can be seen as a doubly linked list of characters rather than an array. Article Link
In some cases it may be preferable to convert the String to an Array, mutate, then convert back to a String, e.g.:
var chars = Array("sometext".characters)
for i in 0..<chars.count {
chars[i] = "c"
}
let string = String(chars)
Advantages include:
Disadvantages include:
Pick your poison :)
c's?