Reputation: 39
How to put a static block in Swift, like here in Java?
I have tried the static var block = {}
but that doesn't work right. It has to called exclusively.
What I want is like in Java, the entire block within the static braces are executed when the class is initialized. Something like that in Swift. I have searched all over the internet and not one soul has an answer! A similar functionality or workaround would also do.
public class EnumRingLevel
{
public static final EnumRingLevel DEFAULT = new EnumRingLevel(
0, 0, "DEFAULT", 1000, 2000);
public static final EnumRingLevel SILENT = new EnumRingLevel(
10, 1, "SILENT", 1001, 2001);
public static final EnumRingLevel QUIET_BEEP = new EnumRingLevel(
20, 2, "QUIET_BEEP", 1002, 2002);
public static final EnumRingLevel NORMAL_BEEP = new EnumRingLevel(
30, 3, "NORMAL_BEEP",1003, 2003);
private final int gdbval;
private final int gindex;
public final String ginternalname;
private final int gcaptionId;
private final int gdisplaycaptionId;
private static EnumRingLevel[] gRingLevelsSortedOnIndex = null;
private static String[] gCaptionsSortedOnIndex = null;
static
{
gRingLevelsSortedOnIndex = new EnumRingLevel[6];
gRingLevelsSortedOnIndex[0] = DEFAULT;
gRingLevelsSortedOnIndex[1] = SILENT;
gRingLevelsSortedOnIndex[2] = QUIET_BEEP;
gRingLevelsSortedOnIndex[3] = NORMAL_BEEP;
gRingLevelsSortedOnIndex[4] = LOUD_BEEP;
gRingLevelsSortedOnIndex[5] = CUSTOM;
gCaptionsSortedOnIndex = new String[6];
for(int i=0;i<gRingLevelsSortedOnIndex.length;i++)
{
gCaptionsSortedOnIndex[i] = gRingLevelsSortedOnIndex[i].getCaption();
}
}
private EnumRingLevel(
int dbval, int index, String internalname
, int captionResource, int displaycaptionResource)
{
//private constructor
gdbval = dbval;
gindex = index;
ginternalname = internalname;
gcaptionId = captionResource;
gdisplaycaptionId = displaycaptionResource;
}
}
Upvotes: 3
Views: 1441
Reputation: 21
try this,
private static var gRingLevelsSortedOnIndex: [EnumRingLevel] = {
return [DEFAULT, SILENT, QUIET_BEEP, NORMAL_BEEP, LOUD_BEEP, CUSTOM]
}()
Upvotes: 2