Fido
Fido

Reputation: 23

RemoveAtIndex crashes playground

I'm trying to remove a Character from a string using the removeAtIndex func of String. But it crashes the playground.

Here is the full code:

let string = "Some String"
let start = advance(string.startIndex, 2)
let x = string.removeAtIndex(start)

Upvotes: 2

Views: 583

Answers (1)

Mike S
Mike S

Reputation: 42325

You've declared string with a let which makes it immutable. Since you can only call removeAtIndex on a mutable String, you can fix this by declaring string with var instead:

var string = "Some String"
let start = advance(string.startIndex, 2)
let x = string.removeAtIndex(start)

Note: The above works in Xcode 6.1, but crashes the compiler in Xcode 6.0.

For Xcode 6.0, using the global removeAtIndex function instead works:

var string = "Some String"
let start = advance(string.startIndex, 2)
let x = removeAtIndex(&string, start)

Upvotes: 2

Related Questions