我刚刚为自己学习了新语言 - 很快,现在我遇到了空值的问题。我编写一个简单的应用程序来搜索数组的最小值和最大值。但是如果在app中输入空值 - crush会发生错误: 致命错误:在解包可选值(lldb)时意外发现nil
我尝试在nil和isEmpty上实现一些检查,但app仍在破碎。
以下是代码:
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var inputArrayValues: NSTextField!
@IBOutlet weak var minLabel: NSTextField!
@IBOutlet weak var maxLabel: NSTextField!
@IBAction func arrayMinMax(sender: AnyObject) {
var someData = inputArrayValues.stringValue
let separators = NSCharacterSet(charactersInString: " ,;:|")
let parts = someData.componentsSeparatedByCharactersInSet(separators)
if (someData.characters.count > 0) {
someData = "0"
}
let intArray = parts.map{Double($0)!} // on that line crush occurs
let minArray = intArray.minElement()
let maxArray = intArray.maxElement()
let minString = String(minArray)
let maxString = String(maxArray)
minLabel.stringValue = "The minimal value is \(minString)!"
maxLabel.stringValue = "The maximal value is \(maxString)!"
}
那么,如何检查nil并防止app崩溃?