mardi 22 septembre 2015

Is there an operator in Swift that stops the evaluation of a multi expression conditional statement, as soon as the answer is clear?

In some programming language there is two other operator in addition with simple || and &&. these operators which I am going to call them _orif and _andif from now, can be used in place of && and || and They may help to improve efficiency and avoid errors, because evaluation of the conditional stops as soon as the answer is clear.

For example, evaluation of the following expression will stop halfway through (selectedSprite != nil) is false: So the rest of the conditional will be ignored and never evaluated, this will prevent a fatal error in this case : fatal error: unexpectedly found nil while unwrapping an Optional value and it will raise while reaches to the second expression because obviously nil does not responds to SpriteOwner().

if (selectedSprite != nil) &&
   (selectedSprite.SpriteOwner().type == "Human")
{
   println("a human selected")
}

I am looking for a replacement for && in above piece of code that could be used instead of the simple && operator, So if the first expression is evaluated as a false one (having the selectedSprite equal to nil) then the second expression be ignored at all.(since it does not have any influence on result)

Question:

Is there such a &&? operator in swift? if the answer is a No,

Is there a better way of doing that instead of nested if statements like I have written here :

if (selectedSprite != nil)
{
    if (selectedSprite.SpriteOwner().type == "Human")
    {
       println("a human selected")
    }
}

I am implementing an intelligent system with a lot of if clause in it and most of them are too complicated which adding a new if layer just to control nils is a real nightmare.

Aucun commentaire:

Enregistrer un commentaire