简体   繁体   中英

Are these two snippets equivalent?

Are both of this snippets the same? Is it possible that on the first one myClass can at some point in the lifetime of the application will be eliminated?

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    private let myClass = MyClass()

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        myClass.doSomething()

    }
}
    

and

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    private var myClass: MyClass?

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        myClass = MyClass()
        myClass?.doSomething()

    }
}

No the two snippets are not equivalent. You can not reassign a let in Swift. In your second snippet the line:

private let myClass: MyClass?

should be:

private var myClass: MyClass?

Assuming that your two snippets don't include any other code that could interact with the variable then it would be the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM