这是我收到的error
错误:执行被中断,原因:EXC_BAD_INSTRUCTION (代码= EXC_I386_INVOP,子代码= 0x0)。
我知道错误是由代码中某个地方的nil
值引起的,但我找不到它。这是任何人对nil
值在哪里有任何见识的代码,将不胜感激。
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()
答案 0 :(得分:0)
我已经为下面的变量提供了默认值
var randomNumber = 0
var challengesArray = [""]
var challengeNumber = 0
var mad : String = ""
var challenge : String = ""
因此,如果您遇到零问题,那么访问上面的内容一定不是问题。因此,请确保您访问所有其他变量(是否为第一个可选)(如果可选),然后使用if let
或guard
以避免在运行时访问nil导致崩溃。