Search code examples
iosswiftfunctionappdelegateuiapplicationdelegate

Static member 'load' cannot be used on instance of type 'AppDelegate'


Can someone explain why I cannot use a custom load function in my application(_, didFinishLaunchingWithOptions:)?

I am receiving the error:

Static member 'load' cannot be used on instance of type 'AppDelegate'

When I rename the function e.g., to func loader(...) and call it with loader("data.json") it works as expected. Does Xcode not recognize correctly that I am using a custom function named load instead of the NSObject.load() function correctly here? I know I can just stick with renaming the function but I would like to understand the root cause for this.

AppeDelegate.swift

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var data: Maturity? = nil

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        data = load("data.json") // Static member 'load' cannot be used on instance of type 'AppDelegate'
        return true
    }
    ...
}

Data.swift

import Foundation

func load<T: Decodable>(_ filename: String) -> T {
    let data: Data

    guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
        else {
            fatalError("Couldn't find \(filename) in main bundle.")
    }

    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
    }

    do {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
}

Solution

  • Swift always calls the most specific overloaded version of a function is several could be called with the same parameters.

    In your specific case, this means that the instance method will be called rather than the global function, since an instance method is more specific to that type than the global function.