问题
I just noticed that a file called ViewController.swift (Interface)
was created automatically by Xcode when I created my first ViewController.
Do classes in Swift have/need interfaces the same as in Objective-C and are created behind the scenes by Xcode?
Can someone be so kind and explain what is the purpose of this file?
ViewController.swift (Interface)
import UIKit
internal class ViewController : UIViewController {
override internal func viewDidLoad()
override internal func didReceiveMemoryWarning()
}
回答1:
In C and Objective-C, you have separate interface (.h) and implementation (.c, .m) files.
- The interface file gives a quick view of all the methods and properties of that class that are available to other code (provided they import the interface file). It is like the chapter index of a book.
- The implementation, on the other hand, is where the actual method code is written.
In Swift, on the other hand, there is no such distinction and classes are automatically available to all your code. The advantage is, of course, that the number of source files in your project is roughly cut in half, and you don't need to go back and forth between the interface file and implementation file while coding (it's all "in one place").
So, to make up for the lack of an "interface-only" file (like the headers in C/Objective-C), Xcode generates one "on the fly" just for the purpose of showing you the available methods and properties of that class. You will notice that method bodies are missing, as well as properties and methods declared as private
(because they are inaccessible outside of the class, hence by definition not part of the "interface").
It is not a real file that resides anywhere in your file system (as far as I know).
回答2:
In swift you don't have separate interface (or header files) and implementation files. You just create the class interface and implementation together in the same file. Other parts of the project, will automatically get access to the type introduced in a given file.
Now coming to the ViewController.Swift, this is the file where your view's controller layer logic goes. Please refer this documentation-
https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/
来源:https://stackoverflow.com/questions/34646516/what-is-the-viewcontroller-swift-interface-file-for-in-counterparts