CoolMAn
CoolMAn

Reputation: 1861

How to create a range for number in swift

I am creating an iOS app and I've run into an obstacle that I need help overcoming. My issue is that my app uses a score counter, and I want the app to give the user certain medals for certain scores. For example if the user scores a 20 I want the app to give them a bronze medal, if the user scores somewhere between 21-49 they get a silver. I hope you get the idea. I've tried this:

if String(score) > 55{
         medal = SKSpriteNode(imageNamed:"medalG")
    }
    var x = 20
    var y = 50

    if (String(score) = x...y){
        medal = SKSpriteNode(imageNamed:"medalS")
    }
    if String(score) < 20{ //this line always gives me issues
        medal = SKSpriteNode(imageNamed:"medalB")
    }

I've tried replacing the second 'if' line with this

if (String(score) = x..<y){ }

yet this also gives me issues

I've also tried...

if String(score)<50 && String(score)>20{ }

but this has also given problems, please somebody help

Upvotes: 1

Views: 1462

Answers (2)

Nik
Nik

Reputation: 1777

You can use the "pattern-match" operator ~=:

if 20 ... 50 ~= String(score) {
    println("success")
}

Or a switch-statement with an expression pattern (which uses the pattern-match operator internally):

switch String(score) {
case 20 ... 50:
    println("success")
default:
    println("failure")
}

for more help Pattern matching

Upvotes: 0

Matthew Burke
Matthew Burke

Reputation: 2364

Range has a method contains that you can use to check to see if a particular value lies between the range's endpoints. But you're probably better off using the switch statement--with its interval matching, it's basically designed for this scenario.

You can do something like the following:

// assume score is an Int defined above
switch score {
   case 0...20:
      medal = SKSpriteNode(imageNamed: "medalB")
   case 21...49:
      medal = SKSpriteNode(imageNamed: "medalS")
   case 50...60:
      medal = SKSpriteNode(imageNamed: "medalG")
   default:
      print("It is inconceivable that you are this good.")
}

Keep in mind that a switch statement has to be exhaustive, that is there must be a case to match every possible value of the expression on which you are switching. That's why I added the default above.

Upvotes: 1

Related Questions