对于Java中的静态块,swift中的等价物是什么

时间:2015-12-03 12:02:42

标签: swift static block

如何在Swift中放置静态块,就像在Java中一样? 我试过了static var block = {} 但那不行。它必须专门打电话。

我想要的就像在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 个答案:

答案 0 :(得分:1)

试试这个,

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