0

I am confused as to how to unwrap an optional value. I am checking to see if my variable has any nil values and i still get an error. I am trying to perform this logic inside of an NSCollectionViewItem. Is it not possible in there? I keep getting this error no matter what I do:

fatal error: unexpectedly found nil while unwrapping an Optional value

import Cocoa

class ImageCollectionView_Item: NSCollectionViewItem {

@IBOutlet weak var label: NSTextField!

var test: String?

override func viewDidLoad() {
    super.viewDidLoad()

    if test != nil {
        print("success")
        label.stringValue = "success"
    } else {
        print("fail")
        label.stringValue = "fail"
    }
  }
}
  • 2
    Where is the error, on `label.stringValue`? Check that the `label` IBOutlet is properly connected. – Eric Aya Oct 05 '16 at 17:59
  • The label is properly connected. I dragged the label to my NSCollectionViewItem and no matter what I do I still get the same error. – Nick Balistreri Oct 05 '16 at 18:07
  • It appears that your error is coming from force-unwrapping `label` not `test`. Despite your assertion that the outlet is connected the app does not appear to agree. Can you provide more detail? It would help to confirm exactly on which line this error is thrown. Additionally if you switch `label` to be an optional I believe you will find that it is currently nil but we don't have enough information here to learn why. – Jonah Oct 05 '16 at 18:43

1 Answers1

1

To unwrap an optional value in a swifty way:

if let t = test {
     //You can use t as the non optional value
     //This if statement will run if test (t) is not nil
     label.stringValue = "success"
}
else {
    //This will run if test is nil
    label.stringValue = "fail"
} 
Entitize
  • 3,933
  • 3
  • 18
  • 28