将带有 NSStrings 的数组转换为 NSDecimalNumber 的最佳方法是什么?
What is the best way to convert an array with NSStrings to NSDecimalNumber?
我有一个 NSArray
里面有 10 个 NSStrings
:
myArray (
@"21.32",
@"658.47",
@"87.32"...
)
将所有 strings
转换为 NSDecimalNumber
的最佳方法是什么?
用for循环会很简单:
myArray (
@"21.32",
@"658.47",
@"87.32"...
)
NSMutableArray *numberArray = [NSMutableArray arrayWithCapacity: myArray.count];
for (aString in myArray)
{
NSDecimalNumber *aNumber = [NSDecimalNumber decimalNumberWithString: aString];
[numberArray addObject: aNumber];
}
NSArray 上的一个非常简单的类别将允许您像在其他语言中看到的那样使用map
@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
现在您可以在您的案例中使用 -map:
,例如
NSArray *array = @[@"21.32",
@"658.47",
@"87.32"];
array = [array map:^id(NSString *element) {
return [NSDecimalNumber decimalNumberWithString:element];
}];
NSMutableArray 就地变体可以是
@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];
}];
我有一个 NSArray
里面有 10 个 NSStrings
:
myArray (
@"21.32",
@"658.47",
@"87.32"...
)
将所有 strings
转换为 NSDecimalNumber
的最佳方法是什么?
用for循环会很简单:
myArray (
@"21.32",
@"658.47",
@"87.32"...
)
NSMutableArray *numberArray = [NSMutableArray arrayWithCapacity: myArray.count];
for (aString in myArray)
{
NSDecimalNumber *aNumber = [NSDecimalNumber decimalNumberWithString: aString];
[numberArray addObject: aNumber];
}
NSArray 上的一个非常简单的类别将允许您像在其他语言中看到的那样使用map
@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
现在您可以在您的案例中使用 -map:
,例如
NSArray *array = @[@"21.32",
@"658.47",
@"87.32"];
array = [array map:^id(NSString *element) {
return [NSDecimalNumber decimalNumberWithString:element];
}];
NSMutableArray 就地变体可以是
@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];
}];