简体   繁体   中英

Swift: Nested Optionals

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.

var theNewInstance = exampleClass?() is creating an optional with an initial value of nil. It's essentially the same as var theNewInstance : exampleClass? = nil 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM