- (NSString *)windDirectionFromDegrees:(float)degrees {
static NSArray *directions;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
directions = @[@"N", @"NNE", @"NE", @"ENE", @"E", @"ESE", @"SE", @"SSE",
@"S", @"SSW", @"SW", @"WSW", @"W", @"WNW", @"NW", @"NNW"];
});
int index = (degrees + 11.25f) / 22.5f; // 每象限 22.5°,+11.25 實現四捨五入
return directions[index % 16];
}
dispatch_once 保證靜態數組只初始化一次,線程安全。NSLog(@"%@", [self windDirectionFromDegrees:180]); // S
NSLog(@"%@", [self windDirectionFromDegrees:45]); // NE
NSLog(@"%@", [self windDirectionFromDegrees:350]); // N
將數組改為 8 元素,除數改為 45° 即可。