Search code examples
swiftstringswift3

String basics with Swift


Just trying to remove the first character from a string in Swift. I use the code written below, but the second line keeps crashing my application.

Is this not the correct way to unwrap a String Index? What is?

var tempText = text
let toRemove = tempText?.startIndex ?? String.Index(0)
tempText?.remove(at: toRemove)

Solution

  • You are initializing a String.Index type instead of getting the index of the tempText string.

    Moreover, startIndex is not an optional, tempText, however, is.

    You should check if tempText exists and is not empty (you can simply do this with an if let), and remove the character at startIndex if it matches those conditions.

    var tempText = text
    
    if let toRemove = tempText?.startIndex {
        tempText?.remove(at: toRemove)
    }