对于Swift中的单身人士课程,最后的必要条件是吗?

时间:2018-07-24 22:51:24

标签: swift singleton final

要创建一个单例类,我写了这样的内容:

class SingletonEx{
    var name = ""
    private init(){}

    static let sharedInstance = SingletonEx()

    func instanceMethod(){  
    }

    static func classMethod(){
    }
}

有些教程说 final 是必要的,而另一些教程只是忽略 final 关键字。在尝试对 SingletonEx 进行子类化后,得到了以下结果。

enter image description here

enter image description here

enter image description here

似乎我不能为子类编写初始化程序,这意味着我不能在子类中使用 override 实例方法。

据我所知,单例定义是关于单个实例化和通过唯一实例访问实例方法的。因此,我认为在单例定义中不必使用 final 。但是我的老师和一些在线教程都说这是必要的。

我很困惑,因为无论如何您都无法创建子类实例,即使您覆盖实例方法,也无法使用或访问它,所以说 final 的意义是什么?一个单身人士班吗?

如果我错了,请指出。

1 个答案:

答案 0 :(得分:0)

Super Class

First of all you need to know the properties and methods that are marked with private are just known to the Super class and Sub classes won't access them!

A class can inherit methods, properties, and other characteristics from another class. When one class inherits from another, the inheriting class is known as a subclass, and the class it inherits from is known as its superclass. Inheritance is a fundamental behavior that differentiates classes from other types in Swift.

Classes in Swift can call and access methods, properties, and subscripts belonging to their superclass and can provide their own overriding versions of those methods, properties, and subscripts to refine or modify their behavior. Swift helps to ensure your overrides are correct by checking that the override definition has a matching superclass definition.

In your case in SingletonEx class you market init with private which means that you can create object just in the body of the class! that means no one, no where, can't create an object of SingletonEx!

If you want to a method end up in Super Class and you don't want to Sub classes overide that method you need to mark that method with final which means it's not private but its available only from Super class!


Sub Class

When class Y Inheritance from SingletonEx which means that cant create an object outside of the class ! because Super class initializer is unavailable during init() method from class Y ! While you need to call the super.init() if you want to initialize an object from Y class !

if you remove private from private init() {} from SingletonEx class you be able to create object from SingletonEx class and also from Y class !


your code should looks like this :

Swift 4 :

class SingletonEx{

   var name = ""

   init(){}

   static let sharedInstance = SingletonEx()

   func instanceMethod(){
   }

   static func classMethod(){
   }
}




class Y : SingletonEx {

   private var yName = "Y name is : "

   init(name:String) {
      super.init()
      self.name =  self.yName + name
   }

}

Usage :

override func viewDidLoad() {
    super.viewDidLoad()

    let yObject = Y.init(name: "badGirl :D ")

    print(yObject)

    // --> Output : Y name is : badGirl :D   
}