我有一个类方法,它应该接受一个对象并填充一些值。这是功能演示阶段,所以后期实施会更好。现在我只想这样做。
在下面的代码中,zoneID整数成功传递给if语句。 rgb double数组不会进入if语句范围。初始化时设置的值使得它一直到了zonePoint.color,而没有在if语句中设置。
下面的代码不会按原样编译。我想知道如何让rgb变量在if语句范围内可见。
(注意:我尝试了在if语句中初始化变量的天真解决方案。这会清除错误,但不会让新的rgb变量超出if范围)
// This method populates properties
+(void)setContantPropertiesForID:(DistrictPoint *)districtPoint
{
int districtID = [districtPoint.districtID intValue];
double rgb[3] = {0,0,0};
if (districtID == 1) {
districtPoint.title = @"District 1";
rgb = {1.0,0.0,0.0}; // error is expected expression
} else if (districtID == 2) {
districtPoint.title = @"District 1";
rgb = {0.0,1.0,0.0};
} else if (districtID == 3) {
districtPoint.title = @"District 1";
rgb = {0.0,0.0,1.0};
} else {
districtPoint.title = nil;
rgb = {1.0,1.0,1.0}; // error condition
}
districtPoint.color = [UIColor colorWithRed:rgb[0] green:rgb[1] blue:rgb[2] alpha:0.5];
}
答案 0 :(得分:2)
这与if语句无关。您可以使用花括号表示法仅在初始化时设置数组的元素(事实上,在代码中较早的时候)。