Search code examples
iosobjective-cnsstringnsarraynsdecimalnumber

What is the best way to convert an array with NSStrings to NSDecimalNumber?


I have an NSArray with 10 NSStrings inside:

myArray (
         @"21.32",
         @"658.47", 
         @"87.32"...
        )

What's the best way to convert all the strings to an NSDecimalNumber?


Solution

  • A very simple Category on NSArray will allow you to use map as seen in other languages

    @interface NSArray (Functional)
    
    -(NSArray *)map:(id (^) (id element))mapBlock;
    
    @end
    

    @implementation NSArray (Functional)
    
    -(NSArray *)map:(id (^)(id))mapBlock
    {
        NSMutableArray *array = [@[] mutableCopy];
        for (id element in self) {
            [array addObject:mapBlock(element)];
        }
        return [array copy];
    }
    
    
    @end
    

    Now you can use -map: in your case like

    NSArray *array = @[@"21.32",
                       @"658.47",
                       @"87.32"];
    
    array = [array map:^id(NSString *element) {
        return [NSDecimalNumber decimalNumberWithString:element];
    }];
    

    A NSMutableArray in-place variant could be


    @interface NSMutableArray (Functional)
    -(void)map:(id (^) (id element))mapBlock;
    @end
    

    @implementation NSMutableArray (Functional)
    
    -(void)map:(id (^)(id))mapBlock
    {
        [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            self[idx] = mapBlock(obj);
        }];
    }
    
    @end
    

    NSMutableArray *array = [@[@"21.32",
                               @"658.47",
                               @"87.32"] mutableCopy];
    
    [array map:^id(NSString *element) {
       return [NSDecimalNumber decimalNumberWithString:element];
    }];