ios how can implement a switchs/case with string? [duplicate] - iphone

This question already has answers here:
Using an NSString in a switch statement
(9 answers)
Closed 9 years ago.
I want to implement a switchs/case where I can use a string to evaluate the switch case.
switch (tmp) {
case one:
NSLog(#"the string value of tmp is one");
break;
any of you knows how can I implement something like this?
I really appreciate your help

You can not use string in switch case statement, you can use only int or char data type.
But as i think your question is to make switch case more easy to understandable or readable.
So you can make enum for that, like:
typedef enum {
zero,//by default the value starts from zero.
one,
two
} NumCount;
At the point you have use it.
NumCount tmp = one;
switch (tmp) {
case one:
NSLog(#"the string value of tmp is one");
break;
}
I think you understand what i want to say. If you have any doubt please ask from me.

Related

Why can't I put an enum case in single quotes which is of type Int? [duplicate]

This question already has an answer here:
Use reserved keyword a enum case
(1 answer)
Closed 4 years ago.
I'm following a tutorial and it says to type in the code below:
import UIKit
enum Theme: Int {
//1
case `default`, dark, graphical
//2
private enum Keys {
static let selectedTheme = "SelectedTheme"
}
//3
static var current: Theme {
let storedTheme = UserDefaults.standard.integer(forKey: Keys.selectedTheme)
return Theme(rawValue: storedTheme) ?? .default
}
}
This seemed to be fine and well however I began researching online what exactly an enum in Swift is. One piece of information I found online said that I could break out each case on its own line as shown below:
import UIKit
//We're creating an enum!
enum Theme: Int {
//1
case 'default'
case dark
case graphical
//2
private enum Keys {
static let selectedTheme = "SelectedTheme"
}
}
However I get a compile time error that says 'Expected identifier in enum 'case' declaration and I'm not sure what this means. Can anyone please explain why can't I break out each case on its own line in this example?
Thanks to the fine comment above for help. The reason is because the word "default" is a keyword that is reserved in the Swift language therefore in order to use it within my own program in a different way than suggested by the Swift language then I will need to place with word within backticks. See this SO question for reference: Use reserved keyword a enum case

Swift switch statement force to write block of code [duplicate]

This question already has answers here:
Noop for Swift's Exhaustive Switch Statements
(8 answers)
Closed 5 years ago.
I have question, i have enum with 3 state. On 2 of 3 that state i want to do something, but for 3rd i do not. However, when i do not put block of code below case, compiler highligh it with red and won't allow me to run app. Example:
func leftBarButtonTappedWithType(type: CustomNavBarViewModel.LeftBarButtonType) {
switch type {
case .none:
print("")
case .back:
self.popViewController(animated: true)
case .hamburger:
self.func()
}
}
You can see that for case .none i wrote print("") because in other case i won't be able to compile. How to avoid that? Kind of ugly.
Just get your function to return in that case:
case .hamburger:
return
Hope that helps.
Per the discussion and #MartinR 's comment, break is probably a better general solution to exit the switch statement.

Using enum and switch case combination in Swift [duplicate]

This question already has answers here:
Switch in Swift - Case label in a switch should have at least one executable statement
(2 answers)
Noop for Swift's Exhaustive Switch Statements
(8 answers)
Closed 7 years ago.
Here is my code:
enum GameScreen
{
case kSceneFlashScreen
case kSceneMainMenu
case kSceneGameScreen
case kSceneStoreScreen
case kSceneGameOver
}
class YSGameManager: NSObject {
func replaceGameScene(inScreen: GameScreen)
{
switch inScreen
{
case GameScreen.kSceneGameScreen: //Error for here
case GameScreen.kSceneMainMenu : //here also error
}
}
}
Eror LOG: 'case' label in a 'switch' should have at least one executable statement
How to use enum in switch case in Swift ?
There's an error because you haven't got anything after : and before the next case. To solve this you can:
1. Add some code to do something.
2. Add fallthrough if you want to move to the next case. This may have been what you were trying to do. However, in Swift, switch statements don't fallthrough by default to the next case, they break.
3. Add break to stop the switch statement.
It’s complaining that you need to actually do something after the matching case. Otherwise there’s not much point matching it, and chances are it’s a typo.
Other possibly than coverage i.e. if you don’t want a default, you want to name every possible enum, even though you don’t want to do anything for some of them. In which case, stick in a break:
switch inScreen {
case kSceneGameScreen:
break
// etc.
}
Note, there’s no implicit fall through in Swift’s switch statements. You need to give one explicitly:
switch inScreen {
case kSceneGameScreen:
// do a game-screen-specific thing
fallthrough // then
case kSceneMainMenu:
// do a thing for both
// kSceneGameScreen and kSceneMainMenu
// etc.
}
But if you just want to match two possibilities, you don’t need to use fall through, you can just combine them with ,:
switch inScreen {
case kSceneGameScreen, kSceneMainMenu:
// do a thing for both
// kSceneGameScreen and kSceneMainMenu
// etc.
}

Reflection of enum in Swift [duplicate]

This question already has answers here:
Swift: Convert enum value to String?
(19 answers)
Closed 7 years ago.
Say I have an enum like this:
enum Direction {
case Left
case Right
}
Is there a way to derive a string description of the enum automatically without defining it myself? Something like this:
let direction: Direction = .Left
let description: String = direction.description // should be "Left"
I tried reflect( direction) and the properties on MirrorType but that didn't work.
Not currently. You'll need to implement a description function manually for this. Swift has very limited reflection.
I think the closest you can do is either implement description yourself or make the enum a string:
enum Direction: String {
case Left = "Left"
case Right = "Right"
}
You can then get the value via direction.rawValue. Obviously, not as great as what you are looking for though and it requires duplicating the enum value, which is dumb.
You can then use the raw value to implement the description if you want (allowing you to use direction.description:
var description: String {
return self.rawValue
}

if else statements confusion Objective-C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In Xcode, I have an if and an else statement.
I would like to make the statement have multiple conditions, but only one of them have to be 'YES'.
For example:
I have a NSString, the value of that string is:
[NSstring stringWithFormat:#"ABCDEFG12345"];
I need to have my if statement check for if A or 1 or 5 is in the string. I understand how to use [string rangeOfString:#"CheckHere"];.
I need my if statement to find one or all of those given letters/numbers. If one is found, execute the given code, if two are found, execute the given code, if all three are found, execute the given code.
You need no if-else. You can do something like this.
NSString* string = #"ABCDEFG12345";
int foundA = [string rangeOfString:#"A"].location == NSNotFound ? 0 : 1;
int found1 = [string rangeOfString:#"1"].location == NSNotFound ? 0 : 1;
int found5 = [string rangeOfString:#"5"].location == NSNotFound ? 0 : 1;
int foundCount = foundA + found1 + found5;
switch(foundCount) {
case 1: [self executeOne]; break;
case 2: [self executeTwo]; break;
case 3: [self executeThree]; break;
}
One possible approach:
Let's assume you can piece together the (actually somewhat tedious) use of rangeOfString and rangeOfCharacter calls together and can write a method like this:
-(NSInteger)numberOfMatchesFoundInString:(NSString*)inputString;
which lets you pass in a string, and returns a 0,1,2... based on how many matches are found.
To use this convenient result in a highly readable way, you can use a switch statement.
NSInteger* matches = [self numberOfMatchesFoundInString:someString];
switch (matches) {
case 0:
//execute some code here for when no matches are found
break;
case 1:
//execute some different code when one match is found
break;
case 2:
//you get the idea
break;
default:
//some code to handle exceptions if the numberOfMatchesFoundInString method went horribly wrong
break;
Of course some people will tell you that this is functionally no different than calling
if (someCondition) {
//do some stuff
}
else if (someOtherCondition) {
//do some different stuff
}
etc...
but really, you can make either one work.
There are a few useful techniques you can use for string comparisons.
If you just need test if your string is one of a list of strings, use something like this:
NSArray *options = #[#"first", #"second", #"third"];
if ([options contains:inputString]) {
// TODO: Write true block
} else {
// TODO: Write else block
}
If you want to check if your string contains at least one character from a set, use NSString -rangeOfCharacterFromSet:.
Unfortunately, if you want to check if your string contains one or more strings, you have no choice but to write it out the long way. If you do it frequently enough, you may choose to write a class category.
- (BOOL)containsAtLeastOneSubstring:(NSArray *)substrings
{
for (NSString *aString in substrings) {
NSRange range = [self rangeOfString:aString];
if (range.location!=NSNotFound) {
return YES;
}
}
return NO;
}
-