“initialize” class method for classes in Swift?

后端 未结 6 1107
日久生厌
日久生厌 2020-12-04 11:55

I\'m looking for behavior similar to Objective-C\'s +(void)initialize class method, in that the method is called once when the class is initialized, and never a

6条回答
  •  广开言路
    2020-12-04 12:28

    There is no type initializer in Swift.

    “Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.”

    Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.


    You could use a type property which default value is a closure. So the code in the closure would be executed when the type property (or class variable) is set.

    class FirstClass {
        class var someProperty = {
         // you can init the class member with anything you like or perform any code
            return SomeType
        }()
    }
    

    But class stored properties not yet supported (tested in Xcode 8).

    One answer is to use static, it is the same as class final.

    Good link for that is

    Setting a Default Property Value with a Closure or Function

    Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.


    Code example:

    class FirstClass {
        static let someProperty = {
            () -> [Bool] in
            var temporaryBoard = [Bool]()
            var isBlack = false
            for i in 1...8 {
                for j in 1...8 {
                    temporaryBoard.append(isBlack)
                    isBlack = !isBlack
                }
                isBlack = !isBlack
            }
    
            print("setting default property value with a closure")
            return temporaryBoard
        }()
    }
    
    print("start")
    FirstClass.someProperty
    

    Prints

    start

    setting default property value with a closure

    So it is lazy evaluated.

提交回复
热议问题