EXC错误指示

时间:2016-03-02 01:15:41

标签: swift

In想知道为什么我一直收到这条错误信息,EXC Bad Instruction可以帮助我并告诉我原因。

这是代码。

 func updateStocks() {
    let stockManager:StockManagerSingleton = StockManagerSingleton.sharedInstance
    stockManager.updateListOfSymbols(stocks)

    //Repeat this method after 15 secs. (For simplicity of the tutorial we are not cancelling it never)
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(15 * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(),
        {
            self.updateStocks()
        }
    )
}

//4
func stocksUpdated(notification: NSNotification) {
    let values = (notification.userInfo as! Dictionary<String,NSArray>)
    let stocksReceived:NSArray = values[kNotificationStocksUpdated]!
    stocks.removeAll(keepCapacity: false)
    for quote in stocksReceived {
        let quoteDict:NSDictionary = quote as! NSDictionary
        let changeInPercentString = quoteDict["ChangeInPercent"] as! String
        let changeInPercentStringClean: NSString = (changeInPercentString as NSString).substringToIndex((changeInPercentString as NSString).length-1)
        stocks.append(quoteDict["symbol"] as! String,changeInPercentStringClean.doubleValue)
    }
    tableView.reloadData()
    NSLog("Symbols Values updated :)")
}
}

包含错误的行是,

let changeInPercentString = quoteDict["ChangeInPercent"] as! String

1 个答案:

答案 0 :(得分:1)

错误表明Swift试图解开nil值,正如您在此行中所述<​​/ p>

let changeInPercentString = quoteDict["ChangeInPercent"] as! String

Swift尝试强制将quoteDict["ChangeInPercent"]的值设置为String,因为您使用as!,而应使用as?,这会将值设置为如果无法找到值,则nil

let changeInPercentString = quoteDict["ChangeInPercent"] as? String

您可以使用??运算符将其设置为默认值。例如,如果您希望默认值为0.0%,则可以使用

let changeInPercentString = (quoteDict["ChangeInPercent"] as? String) ?? "0.0%"

固有问题很可能是quoteDict["ChangeInPercent"]不存在,或quoteDict["ChangeInPercent"]不是字符串 - 它可能是NSString或只是Double值。

例如,如果您发现它应该是NSString,则需要更改转换值的方式

let changeInPercentString: NSString = (quoteDict["ChangeInPercent"] as? NSString) ?? "0.0%"