0

I just studied new language for myself - swift, and now i'm stuck on trouble with empty values. I write simple app that searches min and max of an array. But if enter empty values in app - crush will happen with error: fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

I tried to implement some checks on nil and isEmpty, but app is still crushing.

Here is the code:

 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)!"

    }

So, how to check for nil and prevent app from crush??

  • 1
    Please see the comprehensive answer(s) in the page I've linked to. It contains the basics for debugging your Optionals. And if you're struggling with the concept, see https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330 – Eric Aya Jun 06 '16 at 19:11
  • Ok, even if i made it optional `let intArray = parts.map{Double($0)}` (now it handle nil if appear) then i get an errors in next two lines: missing argument for parameter #1 in call! How to handle that i just have no idea. – Viktor Diuk Jun 08 '16 at 04:09
  • You get `missing argument for parameter #1 in call` on `let minArray = intArray.minElement()` !? I see two options: you made a typo somewhere, or your Xcode is too old (meaning, your Swift version is too old). Fix the typo or update and it will work. Also, you can replace `map` with `flatMap` if you remove `!` after `Double($0)` – Eric Aya Jun 08 '16 at 17:00

0 Answers0