llinards llinards - 1 month ago 5x
Swift Question

Xcode 6.1 - struct instances console error

I'm a beginner in programming world and I choose "Swift" to be my first programming language. Everything so far went great but now I'm learning about structures and instances, how to update them and so on and I'm getting mysterious console error and I can not move further with my project.

So problem.

I created struct called "Tiger.swift". There is properties for that struct such as name, age, etc. In "viewController" I created new variable called myTiger and tried to update it properties and after my created println command in console appears something strange. It compiles and tells me that "build was succesfully" but in console appears something like this.

"My Tiger's name is: Tigger, it's age is 3, it's age is 3 and it's image is Optional()"

And this strange thing is "Optional". Because if I later want to update my instances it does not compiles and shows me :

"My Tiger's name is: Tigger, it's age is 3, it's age is 3 and it's image is Optional()
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) "

There is a link to Git repository ( https://github.com/llinards/lionsandtigers ) in case there isn't a quick solution or a little bug which accidentally I have made.

I would appreciate any help from you!



I took a closer look at your code:

  1. I changed the image property of your Tiger struct to be optional because you don't have a template or placeholder image (if you have one you can set the initial value to that image).
  2. Your storyboard (including your IBOutlets) very pretty screwed up ... I don't know how that happened, I have never seen anything like this before ...
  3. I uploaded a working copy of you project here (It's hard to show that IB-related stuff here, I just deleted and re-added your labels and views).
  4. The relevant code changes I did are the following:

    In your Tiger model object (Tiger.swift) I changed the last line from

    var image = UIImage(named:"")


    var image: UIImage?

    The first error you encountered was because UUImage(named:"") returns nil. In Swift a non-optional type must never ever be nil.

    In your ViewController a changed the Tiger-initializtion to

    Tiger(age: 3, name: "Tigger", breed: "TOne", image: UIImage(named: "t1.jpg"))

    Your println() call shows:

    My Tiger's name is: Tigger, it's age is 3, it's age is 3 and it's image is Optional(UIImage: 0x7f8d78f43c90)

    This is correct since your image is now wrapped into an optional.