Swift programming question from my son

John Shockey john at johncshockey.com
Sat Oct 10 12:09:49 EDT 2015


Owen,

I haven't done a lot with Swift, since my current project predates the
language. I can't make a lot of sense of the error message. It's a
pretty bad one!

But I can see where the difference between the two versions would
matter.

if label.userData != nil
{
    // ...
}

tells you that userData won't be nil within the braces. But

if var userData = label.userData
{
    // ...
}

tells both you AND the compiler that it isn't nil

So in their version userData is typed as a dictionary, but in your son's
version label.userData is still typed as an optional dictionary.

Seems pretty academic, but in fact another thread could set
label.userData to nil, but the "if var" would be protected. But the real
point is about the types.

Possibly (but I have not done a lot with Swift, remember, so I'm a
little unsure of the syntax) adding a couple of "!" operators would make
his version work. Maybe:

    label.userData!["bounceCount"] = (label.userData!["bounceCount"] as!
    Int) + 1

but don't quote me on that without checking it!

My feeling is that comparing something to nil in Swift may be legal, and
sometimes work, but it kind of goes against the grain of the language.

John



More information about the MacTechGroup-discuss mailing list