What is the ViewController.swift (Interface) file for - in Counterparts

ⅰ亾dé卋堺 提交于 2019-12-23 07:22:00

问题


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.

  1. 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.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!