Home > Enterprise >  How can I call function from another swift file
How can I call function from another swift file

Time:08-29

I'm pretty new to swift and I have created separate swift file for data handling. It includes following function.I want call it using another swift file how could I do that.

import Foundation
import CoreData

internal struct DataManager{
    static let shared = DataManager()
    let persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "eduDemo")
        container.loadPersistentStores {(storeDescription,error) in
            if let error = error {
                fatalError("Loading of store failed \(error)")
            }
        }
        
        return container
    }()



@discardableResult func createUser(email:String,password:String) -> Userdetails? {
    let context = persistentContainer.viewContext
    
    let userdetails = NSEntityDescription.insertNewObject(forEntityName: "Userdetails", into: context) as! Userdetails
    
    userdetails.email=email
    userdetails.password = password
    
    do {
        try context.save()
        return userdetails
    } catch let createError{
        print("Failed to create: \(createError)")
    }
    
    return nil
    
}

}

The function that I'm trying to call above function in another swift-file

  @IBAction func registerPressed(_ sender: Any) {
        
        let Email: String =  email.text!
        let Pwd: String = password.text!
        
        DataManager.createUser(email:Email, password: Pwd)
        
     
    } 

But it gives me following error. What I'm doing wrong here.

Instance member 'createUser' cannot be used on type 'DataManager'; did you mean to use a value of this type instead?

CodePudding user response:

This is because you are trying to use instance function on class level. Instead, refer to the singleton shared you created:

DataManager.shared.createUser(...)
  • Related