i am getting a nil value somewhere in my code and i am unsure where it is and how to fix it

Here is the error i am receiving

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

I know the error is caused by a nil value somewhere in the code but i cannot find it. Here is the code is anyone has any insight as to where the nil value is then help would be appreciated.

import UIKit

var randomNumber = 0
var challengesArray = [""]
var challengeNumber = 0
var mad : String = ""
var challenge : String = ""

func ChallengeBankSplitter()  {

    let fileURLProject = Bundle.main.path(forResource: "Challenges", ofType: "txt")
    var readStringProject = ""
    do {
        readStringProject = try String(contentsOfFile: fileURLProject!, encoding: String.Encoding.utf8)
    } catch let error as NSError {
        print ("Failed to read from project")
        print (error)
    }
    challengesArray =  readStringProject.components(separatedBy: ".") as Array
    var arrayLength = challengesArray.count
    randomNumber = arrayLength

}


func ChallengeSelector() {
    ChallengeBankSplitter()
    challengeNumber = Int((arc4random_uniform(UInt32(randomNumber))))
    challenge = challengesArray[challengeNumber]
    print (challenge)
}

ChallengeSelector()

1 answer

  • answered 2018-10-23 08:54 Sandy

    As I can you have given default value for below variable

    var randomNumber = 0
    var challengesArray = [""]
    var challengeNumber = 0
    var mad : String = ""
    var challenge : String = ""
    

    so accessing above must not an issue and if you facing nil issue. So make sure you access all other variable (check first optional or not) if optional then use if let or guard to avoid crash via accessing nil at run time.