Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between override init and required init? - swift

Tags:

I sometimes see a view made like this where there is the same setup() function in two different init methods. What is the difference between the init methods and why is the same setup() being called in both..?

class BigButton: UIButton {      override init(frame: CGRect) {         super.init(frame: frame)         setup()     }      required init?(coder: NSCoder) {         super.init(coder: coder)         setup()     }      fileprivate func setup() {         // set up stuff     } } 
like image 894
BlueBoy Avatar asked Oct 25 '17 07:10

BlueBoy


People also ask

What is override init in Swift?

Override initializer In Swift initializers are not inherited for subclasses by default. If you want to provide the same initializer for a subclass that the parent class already has, you have to use the override keyword.

What is a required init Swift?

Required initializers will be explained in this article. If we write a required modifier before the definition of init method in a class that indicates that every subclass of that class must implement that initializer. There are various things related to required initializer.

What is the difference between init ?() And init () Swift?

There is no functional difference between the two. Both styles will call the same initializer and produce the same value.

Why do we use required init Swift?

Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.


1 Answers

override init(frame: CGRect) is used when you create the view (in this case the button) programmatically.

required init?(coder: NSCoder) is used when the view is created from storyboard/xib.

since the latter is required you must implement its body. However if you are not going to create the button manually the first one is not required and can be omitted

setup is called in both because however you choose to create the button you want to setup its custom behavior so it will work as you intended it to

like image 99
giorashc Avatar answered Sep 24 '22 11:09

giorashc