简体   繁体   English

如何使用属性初始化单例-Swift?

[英]How do you initialize a singleton with properties - Swift?

I am trying to create a singleton that gets initialized with properties.. I know you can initialize by default: 我正在尝试创建一个使用属性进行初始化的单例。.我知道您可以默认进行初始化:

class ApiSharedHelper {
    var someValue:String    

    static let sharedInstance : ApiSharedHelper = {
        let instance = ApiSharedHelper()
        return instance
    }()


ApiSharedHelper.sharedInstance...

And I would just call that sharedInstance and it'll call the constructor. 我只需要调用该sharedInstance即可调用构造函数。 How would I call that shared instance where I'm passing a value for that someValue string to initialize a value? 我该如何在共享实例中传递someValue字符串的值以初始化值的共享实例?

class APIManager {

    class var shared :APIManager {
        struct Singleton {
            static let instance = APIManager()
        }
        return Singleton.instance
    }

    func login(username: String, password: String, success:@escaping (LoginModel?)->()) { ... }

You can call it by : 您可以通过以下方式致电:

APIManager.shared.login(username: txtUsername.text ?? "", password: txtPassword.text ?? "") { (response) in
            print(response ?? "")
    }

you can try this 你可以试试这个

class ApiSharedHelper {
    var someValue:String    
    static let sharedInstance = ApiSharedHelper()
    private init(){
    }
}

ApiSharedHelper.sharedInstance...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM