简体   繁体   English

swift如何知道要导入哪些文件?

[英]How does swift know which files to import?

I'm diving into swift from the land of Objective-C, and I'm curious about swift's importing functionality. 我正从Objective-C领域涉足Swift,并且对Swift的导入功能感到好奇。 I've discovered that there's no need to import my own classes, like so: 我发现不需要导入自己的类,例如:

Objective-C: Objective-C的:

#import <UIKit/UIKit.h>
#import "CustomObject.h"

CustomObject* newObject = ...

Swift: 迅速:

import UIKit
//no need to import CustomObject

var newObject: CustomObject...

My question is, how does swift accomplish this? 我的问题是,如何迅速做到这一点? Where does it look for .swift files to automatically import? 它在哪里寻找自动导入的.swift文件? Is it just any .swift file that's added to your project's target? 仅仅是添加到项目目标中的任何.swift文件吗? I don't want to just handwave this and then get caught by surprise later when something doesn't import like magic! 我不想随便挥动一下,然后在某些东西不像魔术一样进口时就被惊喜吓住了!

I'm not sure I'm going to explain this with grace but here it goes... 我不确定我是否会优雅地解释这一点,但是在这里...

Let's say you're creating an app called Battlefront . 假设您要创建一个名为Battlefront的应用程序。 When you're adding files/classes to your application, they are in fact added to your app's module, the Battlefront module. 当您向应用程序添加文件/类时,实际上它们已添加到应用程序的模块,即Battlefront模块中。 Let's say you created a class called Hero , well, your class is not only Hero , it is Battlefront.Hero but since you're using it in the context of the Battlefront module, there is no need to specify the module name when using your class. 假设您创建了一个名为Hero的类,那么您的类不仅是Hero ,它是Battlefront.Hero但是由于您是在Battlefront模块的上下文中使用它的,因此在使用您的类时无需指定模块名称类。

Imports in Swift works mostly with modules. Swift中的导入主要与模块一起使用。 I suppose you could import a single class in Swift but I haven't tried it so I can't comment on this. 我想您可以在Swift中导入单个类,但是我没有尝试过,因此我无法对此发表评论。 Let's say you're importing CoreData , well you're importing the whole module by using import CoreData . 假设您要导入CoreData ,那么您要使用import CoreData导入整个模块。

By default, classes are using the internal access control. 默认情况下,类使用internal访问控制。 If you wanted to expose classes inside Battlefront to be available to other modules, you'd have to specify your class as public: 如果要在Battlefront公开类以供其他模块使用,则必须将类指定为public:

// Default is internal, not available outside Battlefront
class Hero {

}

// Public class, is available outside Battlefront
public class Weapon {

}

You can read more on Access Control here . 您可以在此处阅读有关访问控制的更多信息 I suppose you could simplify the relationship to Target equals a Module but that would be taking a shortcut. 我想您可以简化与Target等于Module的关系,但这只是捷径。 Could be a start of understanding the concept though. 不过,这可能是理解该概念的开始。

简短的答案:是的,Xcode可访问项目中的所有.swift文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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