How can I return a nil in Swift

I have a subclass of SKSpriteNode called MyGem. There are multiple instances of this class at runtime. They are all in an array of MyGems. At a specific point I would like to find out which MyGem is twinkling.

The problem I am running into is if no MyGem is twinkling. What do I return? I can't return a nil.

'nil' is incompatible with return type 'MyGem'

So what do I return?

I thought of returning the index number of the MyGem in the array class, and then passing -1 if none were twinkling. But that seems kludgy.

func getHighGem() -> MyGem {
   for gem in myGems {
        if gem.twinkling == true {
           return gem
        }
   }
    return nil //this line causes the IDE error
}
Answered by Graphics and Games Engineer in 679974022

You need to return type MyGem?. In swift the ? signifies that the return type can be null.

Accepted Answer

You need to return type MyGem?. In swift the ? signifies that the return type can be null.

How can I return a nil in Swift
 
 
Q