Swift optional binding and SKNode.name

489 views Asked by At

Is there a better way to write the code where I get the name of each SKNode, it just seems a bit long winded.

// eachChild is an SKNode
for eachChild in children {
    var theActualChildName: String
    if let childName = eachChild.name {
        theActualChildName = childName
    } else {
        theActualChildName = "Undefined"
    }
    println("NODE NAME = \(theActualChildName)")
}

I could write, (see below) which works even if there is no name, but if feels bad as its force unwrapping an optional.

// eachChild is an SKNode
for eachChild in children {
    println("NODE NAME = \(eachChild.name!)")
}

I know Swift is all about safety, but it just feels like I am getting bogged down in code and was wondering if there is something I am missing?

EDIT: I have noticed that even though SKNode.name is a String? if you force unwrap it and it has no value it returns and empty String "", I was thinking it would return nil.

EDIT2: Just to note that the answer by Antonio is indeed what I was after, but in the case of SKNode.name when the node is coming from an scene.SKS file it seems that even though no name is specified the node still gets the name "" (Empty string). If you run the code:

let childName = eachChild.name ?? "Undefined"

You will either get the given "Name" or "", you will never get "Undefined" If you set eachChild.name = nil and run the code above you will get "Undefined" I am assuming that the name property is getting set to "" in the *.sks file if no other value is specified.

1

There are 1 answers

3
Antonio On BEST ANSWER

I presume that name is an optional field - you can use the nil coalescing operator:

let actualChildName = eachChild.name ?? "Undefined"