sungwookbaek sungwookbaek - 17 days ago 7
Swift Question

What is different between extension and inherent

I want know about extension.

Case 1.

import Foundation
import Parse

class Room: PFObject, PFSubclassing {
@NSManaged var name: String?

static func parseClassName() -> String {
return "Room"
}
}


case 2.

import Foundation
import Parse

class Room: PFObject {
@NSManaged var name: String?


}

extension Room: PFSubclassing {

class func parseClassName() -> String {
return "Room"
}


}


What is different? Both are working perfectly I just know which one is better and why?

Answer

An extension lets you add functionality to a class (to extend it) without having to subclass.

So imagine you want to add a quickAlertFunction so you can easily display a basic alert with a title, message and ok button:

func displayQuickAlert(title: String: message: String) {
    // create a alert VC with title and mesage
    // add the ok button/action
    // present the alertVC
}

If you done this by subclassing, you would need to update all your ViewControllers to extend from your subclass, but if you done this as an extension of UIViewController you wouldn't need to update anything.

It's generally better to use an extension when you want to add general functionality to a class, if you want to add specific changes, maybe like extending a textfield and adding some autocomplete or something.. you wouldn't want these changes to be global on all Textfields, just instances of your subclass.

Also, One last thing to note.. you cannot add properties in an extension, but you can in a subclass