기존의 UIView에 기능을 추가 해서 사용하는 방법으로는 subclass를 만들어 사용하는 것과 expension을 이용 확대하는 방법이 있다.

단 expension의 경우 stored property를 새로 추가 할수 는 없다. (참조 https://docs.swift.org/swift-book/LanguageGuide/Extensions.html    Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.)



하부 subclass에서 상부의 init()을 이용하는 경우 사용하기 전에 먼저 subclass에서 추가된 property의 값이 할당이 되어야 수행된다. 

Swift has a very clear, specific sequence of operations that are done in initializers. Let’s start with some basic examples and work our way up to a general case.

Let’s take an object A. We’ll define it as follows.

class A {
    var x: Int
    init(x: Int) {
        self.x = x
    }
}

Notice that A does not have a superclass, so it cannot call a super.init() function as it does not exist.

OK, so now let’s subclass A with a new class named B.

class B: A {
    var y: Int
    init(x: Int, y: Int) {
        self.y = y
        super.init(x: x)
    }
}

This is a departure from Objective-C where [super init] would typically be called first before anything else. Not so in Swift. You are responsible for ensuring that your instance variables are in a consistent state before you do anything else, including calling methods (which includes your superclass’ initializer).

subclass 를 이용 추가 property를 사용하는 예시들

class ViewController: UIViewController {

    var imageURL: NSURL?

    // this is a convenient way to create this view controller without a imageURL
    convenience init() {
        self.init(imageURL: nil)
    }

    init(imageURL: NSURL?) {
        self.imageURL = imageURL
        super.init(nibName: nil, bundle: nil)
    }

    // if this view controller is loaded from a storyboard, imageURL will be nil

    /* Xcode 6
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    */

    // Xcode 7 & 8
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

class UIGridCell:UIView {

   var id:String=“”

   override init(frame: CGRect) {

       super.init(frame: frame) // calls designated initializer

   }

   convenience init(id: String) {

       self.init(frame: CGRect.zero)

       self.id = id

   }

   required init?(coder aDecoder: NSCoder) {

       super.init(coder: aDecoder)

   }

}

How do I make a custom initializer for a UIViewController subclass in Swift?

How do I change the font size of a UILabel in Swift?

How to switch to other view controller programmatically in Swift 4?

CORE DATA objectId changes constantly

What is the difference between convenience init vs init in swift, explicit examples better

Tab Bar covers TableView cells in iOS7