Reputation: 55665
Imagine the situation where you have a value you know to be a String, but this string may be a single letter or multiple letters or it may be a digit. Now you'd like to set up a switch statement on this value. You want to run the same block of code for any digit, but don't want to have to write out every single digit in quotes to capture all cases.
This works, but how can it be cleaned up so you don't have to write out every digit possible?
let str = "8"
switch str {
case "a": println("is a")
case "gb": println("is gb")
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" : println("is a digit")
}
Can you either create a range of Ints that are actually Strings and test against that in a case statement, or can you change the value that you're switching on in a case? For example, can you convert the String to an Int and if that is in the range of 0-9 then you know the original String is a digit. Something like case str.toInt() in 0...9
? One solution although even less friendly than the above code would be to create an array of the digits then test if the str
is in the array.
Upvotes: 1
Views: 403
Reputation: 55665
Silly me, it's super simple in Swift. case "0"..."9":
I didn't think it would be smart enough to create a range like that! Very nifty.
Upvotes: 5