ios - is there a way to make this if statement shorter? or easier to maintain? -


i made (rock,paper,scissors) app education, there way make if statement shorter?

this swift code snippet :

var playerselection = "" // possible values r,p,s var cpuselection    = "" // possible values r,p,s var resultstring    = ""  // decide player result if(playerselection == "r") {     if(cpuselection == "r")     {         resultstring = "draw"     }     else if(cpuselection == "p")     {         resultstring = "lose"     }     else if(cpuselection == "s")     {         resultstring = "win"     } } else if(playerselection == "p") {     if(cpuselection == "r")     {         resultstring = "win"     }     else if(cpuselection == "p")     {         resultstring = "draw"     }     else if(cpuselection == "s")     {         resultstring = "lose"     } } else if(playerselection == "s") {     if(cpuselection == "r")     {         resultstring = "lose"     }     else if(cpuselection == "p")     {         resultstring = "win"     }     else if(cpuselection == "s")     {         resultstring = "draw"     } } 

as far know, simplest form educate students how make it, have ideas?

thanks lot

try nested trinary operator check in 1 line using below code

resultstring = ( playerselection == "r") ? (cpuselection == "r" ? "draw" : (cpuselection == "p") ? "lose" : "win") : ((( playerselection == "p") ? (cpuselection == "r" ? "win" : ((cpuselection == "p") ? "draw" : "lose")):((cpuselection == "r" ? "lose" : ((cpuselection == "p") ? "win" : "draw"))))) 

you can use enum , array circulation logic.

please check below code.

enum gameresult : int {     case none = 0     case win = 1     case draw = 2     case lose = 3 }  enum selection : int{      case paper = 1     case rock = 2     case scissor = 3 }  var pselect = selection.paper; var cselect = selection.rock; var result = gameresult.none  var playerrotation = (pselect.rawvalue) % 3 + 1;  if(pselect.rawvalue == cselect.rawvalue){     result = gameresult.draw } else if(playerrotation == cselect.rawvalue){     result = gameresult.win } else{     result = gameresult.lose } 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -