M Zeinstra
M Zeinstra

Reputation: 1981

Swift - Import my swift class

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 my MainScene.swift (I've used Cocos2D - SpriteBuilder to setup the project; Now using Xcode).

This is my folder structure:

enter image description here

I've tried to use import Player; and import 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

Upvotes: 44

Views: 98126

Answers (5)

Chandramani
Chandramani

Reputation: 891

If you getting error like cannot find type "Your_Custome_class" in scope. Just Import the UIKit in project space. or the place you get the error.

for eg :

import Foundation import UIKit // I added this to fix my error.

Upvotes: 0

Nick Fox
Nick Fox

Reputation: 588

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.

Upvotes: 15

Bhagyalaxmi Poojary
Bhagyalaxmi Poojary

Reputation: 1213

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()

Upvotes: 71

Nitish Sharma
Nitish Sharma

Reputation: 31

Check if the class is added to your iOS target in right Pane or not .

Upvotes: 3

Hitendra Solanki
Hitendra Solanki

Reputation: 4941

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. enter image description here

In below image I have unchecked AutolayoutDemo module for the class DetailsViewController.swift.enter image description here

So now onwards when I will try to use the DetailsViewController compiler will give me error as below image in HomeViewController. enter image description here

Upvotes: 31

Related Questions