Switch Case in Swift supports multiple data types, whereas Objective-C only supports integers, because there is always a long code form like this:

if ([str isEqualToString:a]) {
    do a
} else if ([str isEqualToString:b]) {
    do b
} else if ([str isEqualToString:c]) {
    do c
} else if ([str isEqualToString:d]) {
    do d
} else if ([str isEqualToString:e]) {
    do e
}
Copy the code

Through NSDictionary + Block, switch case logic supporting multiple data types can be realized. The key in NSDictionary can be used as the input value of case as long as it conforms to the data type of the protocol. A value in an NSDictionary can be used as a Block to be executed for the corresponding case. The implementation is as follows:

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

typedef void(^HWCaseBlock)(void);

@interface NSObject (HWSwitch)

- (void)switchInCases:(NSDictionary<id<NSCopying>, HWCaseBlock> *)cases;
- (void)switchInCases:(NSDictionary<id<NSCopying>, HWCaseBlock> *)cases withDefault:(nullable HWCaseBlock)defaultBlock;

@end

NS_ASSUME_NONNULL_END
Copy the code
#import "NSObject+HWSwitch.h"

@implementation NSObject (HWSwitch)

- (void)switchInCases:(NSDictionary<id<NSCopying>,HWCaseBlock> *)cases {
    [self switchInCases:cases withDefault:nil];
}

- (void)switchInCases:(NSDictionary<id<NSCopying>,HWCaseBlock> *)cases withDefault:(HWCaseBlock)defaultBlock {
    NSAssert([self conformsToProtocol:@protocol(NSCopying)], @"must confirm to <NSCopying>");
    HWCaseBlock caseBlock = cases[(id<NSCopying>)self];
    if (caseBlock) {
        caseBlock();
    } else if (defaultBlock) {
        defaultBlock();
    }
}
@end

Copy the code

Example:

NSString *str = @"a"; [str switchInCases:@{ @"a": ^{ NSLog(@"A"); }, @"b": ^{ NSLog(@"B"); }, } withDefault:^{ NSLog(@"cannot match the case!"); }]; // Print: A CGFloat floatNum = 1.1; NSNumber *num = @(floatNum); [num switchInCases: @ {@ (1.1) : ^ {NSLog (@ "one point one");}, @ (2.2) : ^ {NSLog (@ "2 point 2");}}]. // Print: 2:2Copy the code

In this way, switch case logic can be used for various data types, such as NSString, NSNumber, and even custom objects, as long as they follow the protocol and can be used as the key of NSDictionary. In addition, the NSNumber type is supported. For float, double, BOOL and other basic data types, the switch case logic can also be used. All you need to do is wrap the @() into an NSNumber (see example above).

Git address, welcome to discuss, improve.