2015-12-03 55 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

相關問題