Swift viewcontroller declaration returning nil

hello world
    let saveNewItem = SaveNewItem()

    print(saveNewItem)

    if saveNewItem != nil {
        print("Contains a value!")
        _ = UIApplication.shared.keyWindow!.rootViewController
        self.present(saveNewItem, animated: true, completion: nil)
    } else {
         print("Doesn’t contain a value.")

    }

I am receiving the infamous: fatal error: unexpectedly found nil while unwrapping an Optional value

on my saveNewItem declaration, which is a call to a different viewcontroller: SaveNewItem from the main one calling this.

I'm confused why this is return nil when the print statement is stating it has a value store in the declaration.

a bypass I figured out to continue the process was to inspect (cmd+click) the saveNewItem constant to which it reproduces in the console my print statement, which gives the impression it creates an object.

I've also tried linking the viewcontroller using the storyboard as demonstated in this question: How to connect ViewController.swift to ViewController in Storyboard?

hello world

Found a way for it to work with no error. These properties had to be called after creating the class object saveNewItem. I overlooked that the SaveLookItems class has properties:

var itemImage     : UIImage!
var imageOrigin   : NSString!
var itemType      : NSString! 

Which require having an initial value other than nil otherwise I get the fatal error: unexpectedly found nil.

So it now works with:

let saveNewItem = SaveNewItem()

print(saveNewItem)

if saveNewItem != nil {
    print("Contains a value!")
        saveNewItem.itemImage = image
        saveNewItem.itemType = "topItem"
        saveNewItem.imageOrigin = "Camera"
    _ = UIApplication.shared.keyWindow!.rootViewController
    self.present(saveNewItem, animated: true, completion: nil)
} else {
     print("Doesn’t contain a value.")

}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related