Learn Swift Fundamentals by preparing for Job Interview, Questions 133 ~ 138 For Extension

Extensions are really useful. This is the reason I like swift the most. Why don’t other languages include this feature? Personally, extension is in my top 3 reasons to love swift.

133) What is extension?

Answer:

  • Way of adding new functionality without subclassing is known as Extension.
class A {	func aFunc() {	}}extension A {

func bFunc() {

}
}let a: A = A()
a.aFunc()
a.bFunc()

134) What is the difference between Subclassing (Inheritance) and Extension?

Answer:

  • No overriding in extension
  • No stored properties in extension (with computed property though, you can)
  • Newly added functionality is available to all instances of that class
class A {	func aFunc() {	}}extension A {

func bFunc() {

}
}let a: A = A()
a.aFunc()
a.bFunc()

135) Can we use stored property in extension?

Answer:

  • No
class A {}// Error 
extension A {
var b: Int = 3
}

136) Can we use computed property in extension?

Answer:

  • Yes, you can declare property with get set
class A {}extension A {
var b: Int {
get {
return 3
}
}
}

137) Can we override existing methods using Extension?

Answer:

  • No, overriding the existing functionality is not allowed in Extension.

138) When to choose Extensions over inheritance?

Answer:

  • Go for extension when you want to add new functionality that should be available for all instances of that class.
  • Go for subclassing when you want to extend the functionality of a class and that should be available for only newly created class. When you want to override the functionality of a class, go for subclassing.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!