1

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)
2
  • What is the crash message? Is the string empty? Commented Sep 22, 2017 at 16:56
  • You may wish to see stackoverflow.com/questions/28445917/… Commented Sep 22, 2017 at 16:59

3 Answers 3

3

You can use Collection method dropFirst:

if let text = text { // you need also to unwrap your optional
    let tempText = String(text.characters.dropFirst())  // And initialize a new String with your CharacterView
}

In Swift 4 String conforms to Collection so you can use it directly on your string:

if let text = text {
    let tempText = text.dropFirst()  // "bc"
}
Sign up to request clarification or add additional context in comments.

Comments

1

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)
}

4 Comments

Thanks, this cleaned it up perfectly. So obvious now that you explained facepalm
Jesus, what's with all the force unwrapping? You already have an if statement, just change it to a conditional binding.
@the4kman Is it really? tempText = tempText?.characters.dropFirst().map(String.init) ?? tempText
@the4kman Sure, but you can unwrap the string index without force unwrapping everythign else ..
0

If you are using swift 4, you can use:

var tempText = text.dropFirst()

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.