UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Project 8 Day 37

Forums > 100 Days of Swift

i have a fatal error here, have no idea what the problem is.

  for (index, line) in lines.enumerated() {
                    let parts = line.components(separatedBy: ": ")
                    let answer = parts[0]
                    let clue = parts[1]        //I get the error on this line, it says :Index out of range

                    clueString += "\(index + 1). \(clue)\n"

3      

Are you sure that the line you are trying to split actually has a second part? If there is no second part, then parts[1] doesn't exist and you will get that error. Stick a print after splitting the line to see what your result is.

3      

I tried to print(parts), but nothing printed, in fact the "print" didn't change colour.

3      

I think its becausse in the level1.txt file, there is an eight line that is empty and swift actually adds that into the array. Paul's file had an 8th empty line but his worked fine, please do you have any suggestions?

3      

I think its becausse in the level1.txt file, there is an eight line that is empty and swift actually adds that into the array.

Yep, that would do it. Since a blank line doesn't contain ":", there would be no part[1] after splitting it.

Paul's file had an 8th empty line but his worked fine, please do you have any suggestions?

Are you sure? I just looked at the files for Project 8 and it doesn't contain a blank 8th line.

Project 8, level1.txt in BBEdit

At any rate, you can fix that by changing:

var lines = levelContents.components(separatedBy: "\n")

to:

var lines = levelContents.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: "\n")

This change will trim off any blank lines at the end of the file before trying to split it into an array.

4      

Ah fantastic! Worked just fine, thank you!

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.