Static block in Swift

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

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

         }
     } 
 }

How to translate this code in Swift?

+5
source share
2 answers

I struggled with the same issue for the last couple of days. The solution I found (although somewhat elegant) is to usemain.swift .

This is not the same as a static block in a class in Java, but it can help in your specific problem.

0
source

You could do something like this.

class SomeViewController : UIViewController {
    public static let formatter: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd"
        return df
    }()
}
0
source

All Articles