7

In Java, I use static block to execute some code when the class is called like in this example"

Class Name
 {
     static
     {
         for(int i = 0; i<10; i++)
         {

         }
     } 
 }

How do I translate that code in Swift?

Cesare
  • 9,139
  • 16
  • 78
  • 130
kaneyip
  • 1,237
  • 1
  • 17
  • 21
  • 3
    possible duplicate of ["initialize" class method for classes in Swift?](http://stackoverflow.com/questions/24137212/initialize-class-method-for-classes-in-swift) – Alex Zielenski Jul 24 '14 at 05:43

2 Answers2

4

You could do something like this,.

class SomeViewController : UIViewController {
    public static let formatter: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd"
        return df
    }()
}
Anand Rockzz
  • 6,072
  • 5
  • 64
  • 71
0

I have been struggling with this same question for the last couple days. The solution that I found (although somewhat inelegant) is the use of main.swift.

This isn't really the same thing as a static block on a class in Java, but it may help with your particular issue.