2015-12-03 41 views
3

如何把一个静态块在Swift中,就像在Java中一样? 我试过了static var block = {} 但这并不正确。它必须专门调用。在Java中的静态块快速等效什么是

我想要的就像在Java中一样,当初始化类时,静态花括号内的整个块都会执行。类似Swift中的那样。我在互联网上搜索过,没有一个灵魂有答案!类似的功能或解决方法也可以。

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; 

    } 
} 

回答

1

试试这个,

private static var gRingLevelsSortedOnIndex: [EnumRingLevel] = { 
    return [DEFAULT, SILENT, QUIET_BEEP, NORMAL_BEEP, LOUD_BEEP, CUSTOM] 
}() 
+0

嗯..我看..不错 – faruk

相关问题