斷言
@implemenetation Triangle
...
-(void)setAngles:(NSArray *)_angles {
self.angles = _angles;
NSAssert((self.angles.count == 3), @"Triangles must have 3 angles. Array '%@' has %i", self.angles, (int)self.angles.count);
CGFloat angleA = [self.angles[0] floatValue];
CGFloat angleB = [self.angles[1] floatValue];
CGFloat angleC = [self.angles[2] floatValue];
CGFloat sum = (angleA + angleB + angleC);
NSAssert((sum == M_PI), @"Triangles' angles must add up to pi radians (180°). This triangle's angles add up to %f radians (%f°)", (float)sum, (float)(sum * (180.0f / M_PI)));
}
這些斷言確保你不會通過丟擲異常來給出三角形不正確的角度。如果他們沒有丟擲異常而不是三角形,根本不是真正的三角形,可能會在以後的程式碼中引起一些錯誤。