How Swift handles objc class method initialize equivalent

Asked 1 years ago, Updated 1 years ago, 51 views

I'm rewriting a sample of Aaron Hiregas' MAC OS X COCOA programming with Swift and it's stuck in the title.

"Each class receives the message initialize before it receives any message," and I wrote a code similar to the following in order to implement this class method in Swift.

import Foundation

classACclass:NSObject {
    override class func initialize() {
        print ("initialized")
    }

    US>func hello() {
        print ("hello")
    }
}

let a1 = ACclass()
let a2 = ACclass()

a1.hello()
a2.hello()

// I hope the results will be as follows.
// initialized
// hello
// hello

The result is

Method 'initialize()defines Objective-C class method 'initialize', which is not permitted by Swift

The error occurred.

I'm looking for another way because it can't be helped that it's not permanent. Is there a good way?

swift swift5

2022-09-30 21:44

2 Answers

Swift's development team banned Objective-C class methods such as initialize and load because the behavior changes due to non-deterministic factors such as execution environment and execution status, making it difficult to guarantee operation.(Unfortunately, I couldn't find any trace of the discussion right away.)

If you want to initialize a class, I think it's the Swift way to prepare an initialization method and explicitly call it when you start the app.

As mentioned above, it is difficult to reproduce the behavior of initialize (but I am not sure how "before") in Swift, but it can be achieved like this if it is "before using the first instance."

import Foundation

classACclass:NSObject {
    private static let initialization:Void={
        print ("initialized")
    }()

    override init() {
        _=ACclass.initialization
    }

    US>func hello() {
        print ("hello")
    }
}

let a1 = ACclass()
let a2 = ACclass()

a1.hello()
a2.hello()

Run Results

initialized
hello
hello

I think the practice of rewriting Objective-C code with Swift is one of the effective ways to learn Swift language, but there is also a negative effect of "I tend to write Objective-C code with Swift grammar."I think it's good to get into the habit of always thinking, "Is this a Swift code?"


2022-09-30 21:44

How to write your own research

Note: https://tech-blog.sgr-ksmt.org/2016/09/25/once_closure/

fileprivate typealias OnceClosure=(()->Void)?
fileprivate func execute_once(_execute:()->Void)->OnceClose{
    execute()
    return {return nil}()
}

classACclass:NSObject {
    fileprivate static var exec_once:OnceClose=execute_once {
        print ("initialized")
    }

    override init() {
        super.init()
        US>ACclass.exec_once?()
    }

    US>func hello() {
        print ("hello")
    }
}


2022-09-30 21:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.