整個事情可以用數據完成,沒有if
s,沒有switch
es ......它只是需要組織一點點。考慮以下幾點:
@property (strong, nonatomic) NSArray *distanceIndex;
@property (strong, nonatomic) NSArray *weightIndex;
@property (strong, nonatomic) NSArray *distanceConversion;
@property (strong, nonatomic) NSArray *weightConversion;
- (void)initConversions {
// we get strings in as our units, so we need to convert these to array indexes
// make up our own convention, meters=0, inches=1, etc
self.distanceIndex = @[@"meters", @"inches", @"miles"];
self.weightIndex = @[@"grams", @"ounces", @"pounds"];
// you might read these from a file, but in code, just to illustrate...
// the order follows the order of the index. so the meters line is first
// and the conversion factors are meters->meters, meters->inches, meters->miles etc.
// notice the 1.0's on the diagonal, and that numbers reflected across
// the diagonal are reciprocals
self.distanceConversion =
@[ @[@"meters", @[@1.0, @39.37, @0.000621]],
@[@"inches", @[@0.254, @1.0, @0.00001578]],
@[@"miles ", @[@1609.0, @63360.0, @1.0]] ];
// and so on... same thing for self.weightConversions
}
- (double)convertDistance:(double)value from:(NSString *)fromUnits to:(NSString *)toUnits {
NSUInteger fromIndex = [self.distanceIndex indexOfObject:fromUnits];
NSUInteger toIndex = [self.distanceIndex indexOfObject:toUnits];
// throw an exception if passed units that we don't recognize
NSAssert(fromIndex != NSNotFound && toIndex != NSNotFound, @"could not find units");
NSArray *conversionRow = self.distanceConversion[fromIndex][1];
NSNumber *conversionNumber = conversionRow[toIndex];
double conversion = [conversionNumber doubleValue];
return value * conversion;
}
- (double)convertWeight:(double)value from:(NSString *)fromUnits to:(NSString *)toUnits {
// same idea here, if you have the weight conversion data
return 0;
}
謝謝!很有幫助。 – user3194296