1

I'm a fairly inexperienced programmer (mainly done AppleScript before), coming to terms with learning Swift - so please go gently!

I'm trying to set up a situation where I have an optional instance variable inside an optional class instance. If I set the instance variable to a value, would this automatically set the class instance to a non-nil value? I'm guessing not, because I'm getting nil...

Here's some distilled example code:

    class exampleClass
    {
        var optionalString: String?
    }


    var theNewInstance = exampleClass?()

    theNewInstance?.optionalString = "dave"



    let theTest1 = theNewInstance?.optionalString!

    println ("theTest1 is: \(theTest1)") // Prints 'theTest1 is: nil'

I've looked through Swift Optional of Optional but I just don't get this protocol business yet... Will keep watching the Stanford CS193P videos...

I'm clearly not understanding something fairly fundamental - could anyone enlighten me please?

Many thanks.

Community
  • 1
  • 1
Moisie
  • 45
  • 1
  • 6

1 Answers1

1

var theNewInstance = exampleClass?() is creating an optional with an initial value of nil. It's essentially the same as var theNewInstance : exampleClass? = nil.

You need to actually create a non-nil instance of it before setting the inner property:

theNewInstance = exampleClass()

Or just don't make it an optional if you are just going to initialize it when you declare it anyway.

dan
  • 9,695
  • 1
  • 42
  • 40
  • Thanks Dan - that's the ticket. In my actual application, exampleClass has a number of optional instance variables, and I want the instance of it to be non-nil only if at least one of those variables is set. Using your guidance, I'll check for whether the instance is nil and, if so, initialise it before setting each of those variables. – Moisie Sep 01 '15 at 18:10