1
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

2
  • You want to end up with a string with only c's? Commented Jan 29, 2016 at 15:44
  • @Eendje Its just for demonstration, but in this case, yes. Commented Jan 29, 2016 at 15:50

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You, great answer!
0

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:

  1. clarity
  2. better performance on large strings: O(1) time for making each replacement in Array vs O(N) time for making each replacement in String.

Disadvantages include:

  1. higher memory consumption: O(N) for Array vs O(1) for String.

Pick your poison :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.