Initializers in Swift 2

0

Could someone explain to me in a simple and clear way the difference between designated initializers and convenience initializers? If possible, with some basic example to understand it

    
asked by Damian Ricobelli 08.06.2016 в 18:13
source

1 answer

2

A class has a designated initializer, however, it may have several convenience initializers. The convenience initializers are helpers, they have to invoke the designated initializer of the same class, yes or yes (e.g. self.init(name: name, age: 8) ), to initialize the class. The convenience initializers are used because they are convenient , they usually have fewer parameters, giving a default value to the other parameters.

  • Example 1 : A class

    class Animal {
        var name: String
        var age: Int
    
        // designated initializer
        init(name: String, age: Int) {
            self.name = name
            self.age = age
        }
    
        /// convenience initializer, gives a default age value
        convenience init(name: String) {
            self.init(name: name, age: 8)
        }
    }
    let dog = Animal(name: "Beethoven")
    print(dog.name)
    
  • Example 2 : A UIView subclass (without storyboard / xib)

    UIView is a special case because it has two initializers, init(frame:) (when the view is initialized programmatically) and also init(coder:) (when the view is initialized from a storyboard or nib, that we can ignore because only Xcode calls this method when it creates the view from the storyboard / xib).

    class AnimalView: UIView {
        var name: String
        var age: Int
    
        // designated initializer
        init(name: String, age: Int) {
            self.name = name
            self.age = age
            super.init(frame: CGRectZero)  // invocamos al designated initializer del superclass
        }
    
        /// convenience initializer, gives a default age value
        convenience init(name: String) {
            self.init(name: name, age: 8)
        }
    
        // No vamos a llamar a este método
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    let dog = AnimalView(name: "Beethoven")
    print(dog.name)
    
  • answered by 14.06.2016 / 01:17
    source