首页 > 解决方案 > 类型“示例”没有成员“共享实例”

问题描述

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

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

标签: iosswiftsingleton

解决方案


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

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"

    }
}

推荐阅读