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()
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()
Answer:
- No
class A {
}
// Error
extension A {
var b: Int = 3
}
Answer:
- Yes, you can declare property with get set
class A {
}
extension A {
var b: Int {
get {
return 3
}
}
}
Answer:
- No, overriding the existing functionality is not allowed in Extension.
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.
Section 3, Conditional Statement
Section 10, static type vs dynamic type
Section 15, higher order function
Section 17, extension