daredevil1234 daredevil1234 - 25 days ago 8
Swift Question

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)

Answer Source

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, and remove the character at startIndex if it matches those conditions.

var tempText = text

if tempText != nil,
    !tempText!.isEmpty {
    let toRemove = tempText!.startIndex
    tempText!.remove(at: toRemove)