TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Error when trying to access non-static method from a static method

Forums > Swift

I am getting "Instance member 'downloadResults' cannot be used on type 'DataStore'" error when trying to access a non-static method from a static method. Is it possible to do this or should I make the non-static method static?

struct DataStore {
  private func downloadResults() {
    print("downloading results")
  }

  static func getResults() throws {
    do {
      let json = try loadJsonFile(fileName: "results")
      print(json)

      if json == "" {
        downloadResults()
      }

    } catch {
      throw DataStoreError.undefinedError(error.localizedDescription)
    }
  }
 }

   

Imagine making five instances of the Datastore structure. Call them struct01, struct02, struct03, struct04, and struct05.

Now call the static method Datastore.getResults() in a button somewhere in your view.

You're asking the getResults() method to call another method named downloadResults() But WHICH downloadResults() method should it call??! There are five Datastore objects in your application. Each one of them has a downloadResults() method.

Each one has a downloadResults() method

struct01.downloadResults() // 👈🏼 This is a non-static function existing in an instance of the struct Datastore            
struct02.downloadResults() // 👈🏼 Also this           
struct03.downloadResults() // 👈 So is this         
struct04.downloadResults() // 👈 So is this
struct05.downloadResults() // 👈 So is this

Which of these methods should the static method call?

This is why you can't access a non-static method from a static method. Swift has no idea which one to call.

   

Perhaps you should be looking at where and how often you use the DataStore. Would it make sense to create the DataStore when your app initialises and pass it to your views as an environmentObject? That way, you only have one instance in existance and it is shared with any view that needs access to it. No need for static functions at all.

Steve

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.