Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在静态函数中使用计算值_Ios_Swift - Fatal编程技术网

Ios 在静态函数中使用计算值

Ios 在静态函数中使用计算值,ios,swift,Ios,Swift,我有一个静态函数,我需要在其中使用一个计算值。该功能的布局如下: fileprivate static func getToken() { var request = URLRequest(url: URL(string: Constant.AuthRequestURL.Values.IDTokenURL)!,timeoutInterval: Double.infinity) request.addValue(getUserAgent(), forHTTPHeaderField:

我有一个静态函数,我需要在其中使用一个计算值。该功能的布局如下:

fileprivate static func getToken() {
var request = URLRequest(url: URL(string: Constant.AuthRequestURL.Values.IDTokenURL)!,timeoutInterval: Double.infinity)
        request.addValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        request.addValue(Constant.AuthRequestHeader.Values.ContentType, forHTTPHeaderField: "Content-Type")
}
目前,我无法运行这段代码,因为它无法访问
getUserAgent()
,我已尝试使用此块在上面的类级别上定义它:

func getUserAgent() -> String {
       let app = "default"
       let version = Bundle.main.infoDictionary["CFBundleShortVersionString"] as? String
       let bundleId = Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String
       let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String
       let iOS = UIDevice.current.systemVersion
       userAgent = "\(app)/\(version ?? "6.2.1")) (\(bundleId ?? "default"); build:\(build ?? "1014"); x86_64; iOS \(iOS); scale:2.0)"
       return userAgent
       }

我猜我定义函数的方式有问题,因为我没有用它作为成员实例化对象?如何让静态函数在运行时访问该函数以生成UserAgent字符串?

请阅读静态方法与实例方法

实例方法要求已经初始化了类的实例,您可以从类的实例调用这些方法

静态方法不附加到类的特定实例,可以在任何地方调用。因此,它们无法访问特定于类实例的方法,因为静态方法无权访问类实例

例如:

因此,您有几个选择:

1-使您的静态方法不是静态的,这样当调用它时,它将有一个类的实例来调用非静态方法

2-将非静态方法设为静态,这样就可以从其他静态方法调用它,而不需要类的实例

3-在静态方法中创建类的实例,并从该类实例调用非静态方法

希望我解释得足够好,有道理

class Thing() {

    var a = 0

    func doThing() {
        // is called from an instance of Thing meaning it can access `a`
        a = 1
        print(a)  // prints 1
    }

    static func doOtherThing() {
        // can be called from anywhere so there is no guarentee `a` exists.
        // in fact it's guarenteed that from the context of this method `a` does not exist

        // but we could make an instance of thing
        let thing = Thing()

        print(thing.a) // prints 0
        thing.doThing() // prints 1
        print(thing.a) // prints 1

        // and we could have a different thing
        let thingTwo = Thing()
        print(thing.a != thingTwo.a) // True since its 1 != 0
    }
}