类型“ example”没有成员“ sharedInstance”

时间:2018-06-29 07:07:54

标签: ios swift singleton

我创建了类,并编写了名为“ example”的单例函数

import UIKit

class example: NSObject {

class example {
    static let sharedInstance = example()
    var userInfo = (ID: "bobthedev", Password: 01036343984)
    // Networking: communicating server
    func network() {
        // get everything
    }
    private init() { }
}

}

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
    super.viewDidLoad()
    example.sharedInstance.userInfo
    // (ID "bobthedev", Password 01036343984)

    // ViewController One
    example.sharedInstance.userInfo.ID // "bobthedev"


}

但是我收到错误消息 *类型'example'没有成员'sharedInstance'*

https://learnswiftwithbob.com/course/object-oriented-swift/singleton-pattern.html

3 个答案:

答案 0 :(得分:2)

您创建了一个嵌套类。 只需跳过内部声明:

import UIKit

class Example: NSObject {
    static let sharedInstance = Example()
    var userInfo = (ID: "bobthedev", Password: 01036343984)
    // Networking: communicating server
    func network() {
        // get everything
    }
    private override init() { }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        Example.sharedInstance.userInfo
        // (ID "bobthedev", Password 01036343984)

        // ViewController One
        Example.sharedInstance.userInfo.ID // "bobthedev"

    }
}

答案 1 :(得分:1)

您已经在示例中嵌入了示例类,因此在执行example.sharedInstance时,它是外部的,因此只需删除外部示例类即可。

答案 2 :(得分:1)

类名应以大写字母开头。 无需在类内部声明类,而需要为单例声明变量,请检查以下代码。

class Example {
    class var sharedInstance: Example {
            struct Singleton {
                static let instance = Example()
            }
            return Singleton.instance
        }
    var userInfo = (ID: "bobthedev", Password: 01036343984)
    // Networking: communicating server
    func network() {
        // get everything
    }
    private init() { }
}






class ViewController: UIViewController {
    override func viewDidLoad() {
    super.viewDidLoad()
    Example.sharedInstance.userInfo
    // (ID "bobthedev", Password 01036343984)

    // ViewController One
    example.sharedInstance.userInfo.ID // "bobthedev"


}