swift - Remove repeated code possible, is there a more elegant solution? -


i'm new swift...

i loop through hand of cards (not shown below), , compare each card determined best option. if has better value, replace struct variable "bestoption" card , appropriate value (penaltyvalue, arbitrary, can -5, -1, 9, 199, doesn't matter question).

so each card in hand call "comparereplacebestoption" card.

the bestoption variable, struct, empty (none value) , therefor filled first card , value. each following card compare (and possibly replace) card value in bestoption variable (which of value).

this code ugly several reasons (all advice appreciated), strikes me double assignment variable bestoption (a struct).

question: there more elegant solution there 1 assignment (i create small function assignment, end conceptually same issue)

having statement twice hurts...

    bestoption = ( card                  , newpenaltyvalue                  ) 

(side information: g.cardstack[0] in previous turn played card face on stack. handcards compared card)

    //find penalty , card card in hand lowest possible penalty     //and without using bonuschip     var bestoption: (card: card!, penaltyvalue: int!)?      func comparereplacebestoption(card: card) {         let newpenaltyvalue = card.nr - g.cardstack[0].nr - 1         if bestoption == nil {  bestoption = ( card                                              , newpenaltyvalue                                              )                              }  else                              {  if ( newpenaltyvalue < bestoption!.penaltyvalue ) {                                      bestoption = ( card                                                   , newpenaltyvalue                                                   )                                 }                              }     } 

updated swift 3.0:

if let best = bestoption, best.penaltyvalue > newpenaltyvalue {     best = (car, newpenaltyvalue) } 

(really losing where clause.)


old updated answer:

after revisiting answer, think can improve make more swifty:

if let best = bestoption best.penaltyvalue > newpenaltyvalue {     best = (car, newpenaltyvalue) } 

we use optional unwrapping feature , where-clause provide addition cases check against (even using now-unwrapped best). easier read , drop pesky !.


original answer:

how about:

if bestoption == nil || newpenaltyvalue < bestoption!.penaltyvalue {     bestoption = (car, newpenaltyvalue) } 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -