Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP,subcode=0x0)

时光总嘲笑我的痴心妄想 提交于 2019-12-24 17:29:58

问题


So close to actually getting this app moving. There is just one more problem. Now, my app will run, and it will give me an error when the next view controller is trying to show. I am showing a ViewController with a quote and an author. I get this error

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP,subcode=0x0)

The output is as follows:

fatal error: unexpectedly found nil while unwrapping an Optional

This is the code with the error:

import Foundation
import UIKit
import Social

class businessQuote: UIViewController {

//============================//
//********** Outlets *********//
//============================//

let utility = Utility()
@IBOutlet weak var quoteDisplay: UILabel!
@IBOutlet weak var authorDisplay: UILabel!
  //GET BACK TO THIS

//============================//
//********** General *********//
//============================//

let date = NSDate()
var Author: String = ""
var Quote: String = ""

override func viewDidLoad() {
    super.viewDidLoad()

    // Generates Random Number
    func randomNumber(arrayLength: Int) -> Int {
        let unsignedArrayCount = UInt32(arrayLength)
        let unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
        let randomNumber = Int(unsignedRandomNumber)


        return randomNumber
    }

    // Importing Quotes plist File
    let businessQuote = ImportList(FileName: "BusinessList")

    // Selects Quote
    let chosenQuote: String = businessQuote.array[randomNumber(businessQuote
        .count())] as! String
    let chosenAuthor = ((businessQuote.dict[chosenQuote]))! as String //This Is Where the error is


    // Assigns Quote & Author to IBOutlet
    Author = chosenAuthor
    Quote = chosenQuote

    quoteDisplay.text = Quote
    authorDisplay.text = Author.uppercaseString

}

}

Thank you in advance!


回答1:


Its due to use of force unwrapping it is crashing .

Best practise to use IF LET to check data is there or not , since IF LET does it (unwrapping ) .

This way Try once : 
if let mStringvalue = businessQuote.dict[chosenQuote]{
  print(mStringvalue)
}


来源:https://stackoverflow.com/questions/36871398/thread-1-exc-bad-instruction-code-exc-1386-invop-subcode-0x0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!