Swift - Import my swift class
Solution 1
You don't need to explicitly import files in Swift as they are globally available through the project. If you want to access the methods or properties of Player class
, you can directly make object of Player class in MainScene.Swift
file and can access to it.
e.g var objPlayer = Player()
Solution 2
There is no need to import swift classes to use in other swift classes. They are available to use automatically.
In Swift you can only import module, e.g. any framework like UIKit, MapKit as below. You cannot import swift classes.
import UIKit
import MapKit
Just make sure its selected to use in target in which your are trying to use.
Check below images for more idea.
In this image my HomeViewController.swift
is selected to use in AutolayoutDemo
module.
In below image I have unchecked AutolayoutDemo
module for the class DetailsViewController.swift
.
So now onwards when I will try to use the DetailsViewController
compiler will give me error as below image in HomeViewController
.
Solution 3
When it comes to Swift imports, there are two cases:
1) The type to import is in the module
In this case, no import statement is needed. As long as the type is not private
or fileprivate
, you can directly access it.
2) The type to import is outside of the module
You can import an entire module using:
import ModuleName
If you only want to import a specific type or function from the module, you can do this using the following format:
import kindOfThing ModuleName.Type
where kindOfThing is class
/struct
/func
/etc...
A much deeper exploration of this can be found on NSHipster here.
Solution 4
Check if the class is added to your iOS target in right Pane or not .
Comments
-
M Zeinstra about 4 years
This question is asked several times, but I can't find the right solution for my problem. I'm trying to import my
Player.swift
class in myMainScene.swift
(I've used Cocos2D - SpriteBuilder to setup the project; Now using Xcode).This is my folder structure:
I've tried to use
import Player;
andimport Player.swift;
, but when I tried I got this error: No such module 'Player.swift'How do I import it correctly?
Thanks!
By the way, I'm a beginner in Swift, so don't expect that I know all of the terms
-
owen gerig about 6 yearsFYI i had created a folder and the auto linking did not work. i had to move them into a group and then it worked.
-
ScottyBlades over 5 yearsI tested this by creating a project where one
.swift
file hasimport UIkit
and another does not. Sure enough, Xcode threw errors and I thought aha! this answer is wrong. But then I remembered that UIKit is an Objective C framework, not a Swift Framework. -
Erhannis almost 4 yearsNote that you can import a single class, if you really want to - see Nick Fox's answer.