How do I import a Swift file from another Swift file? How do I import a Swift file from another Swift file? swift swift

How do I import a Swift file from another Swift file?


I had the same problem, also in my XCTestCase files, but not in the regular project files.

To get rid of the:

Use of unresolved identifier 'PrimeNumberModel'

I needed to import the base module in the test file. In my case, my target is called 'myproject' and I added import myproject and the class was recognised.


UPDATE Swift 2.x, 3.x, 4.x and 5.x

Now you don't need to add the public to the methods to test then.On newer versions of Swift it's only necessary to add the @testable keyword.

PrimeNumberModelTests.swift

import XCTest@testable import MyProjectclass PrimeNumberModelTests: XCTestCase {    let testObject = PrimeNumberModel()}

And your internal methods can keep Internal

PrimeNumberModel.swift

import Foundationclass PrimeNumberModel {   init() {   }}

Note that private (and fileprivate) symbols are not available even with using @testable.


Swift 1.x

There are two relevant concepts from Swift here (As Xcode 6 beta 6).

  1. You don't need to import Swift classes, but you need to import external modules (targets)
  2. The Default Access Control level in Swift is Internal access

Considering that tests are on another target on PrimeNumberModelTests.swift you need to import the target that contains the class that you want to test, if your target is called MyProject will need to add import MyProject to the PrimeNumberModelTests:

PrimeNumberModelTests.swift

import XCTestimport MyProjectclass PrimeNumberModelTests: XCTestCase {    let testObject = PrimeNumberModel()}

But this is not enough to test your class PrimeNumberModel, since the default Access Control level is Internal Access, your class won't be visible to the test bundle, so you need to make it Public Access and all the methods that you want to test:

PrimeNumberModel.swift

import Foundationpublic class PrimeNumberModel {   public init() {   }}


In the Documentation it says there are no import statements in Swift.

enter image description here

Simply use:

let primNumber = PrimeNumberModel()