简体   繁体   中英

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. I've discovered that there's no need to import my own classes, like so:

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? Is it just any .swift file that's added to your project's target? 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 . When you're adding files/classes to your application, they are in fact added to your app's module, the Battlefront module. 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.

Imports in Swift works mostly with modules. I suppose you could import a single class in Swift but I haven't tried it so I can't comment on this. Let's say you're importing CoreData , well you're importing the whole module by using import CoreData .

By default, classes are using the internal access control. If you wanted to expose classes inside Battlefront to be available to other modules, you'd have to specify your class as 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. Could be a start of understanding the concept though.

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

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