Summary of the use and contrast of overrides and overloads in Swift
- 2020-05-30 21:10:31
- OfStack
preface
Recently in learning, swift feel Swift is 1 bag type of language, I'll record 1 some thought before I met less or grammatical features, to remember here as sharing, this paper introduces the related contents about Swift rewrite and overloading, study share out for your reference, the following few words said, to 1 up have a look at the detail.
1. Heavy load:
Function name is the same, parameter name/parameter type/parameter number is different Overloaded functions are not limited to constructors Function overloading is an important symbol of the programming language OC does not support function overloading, the alternative to OC is withXXX...2. Rewrite:
Also called override, it defines a method in a subclass that has the same parameter list as the method in the parent class. Overrides are subclass methods that override parent methods, requiring the method name and parameters to be the same Because a subclass inherits the methods of its parent class, overwriting is redefining the methods inherited from the parent class once, refilling the code in the method. Overrides must inherit, overrides do notSuppose we have an Person class for the "name" and "age" properties, and we add properties to it with the override and override methods, respectively
Create Person class
class Person: NSObject {
var name: String // The name
var age: Int // age
// The constructor
init(name: String,age: Int) {
self.name = name
self.age = age
// Must be in super.init() before Initialization object
super.init()
}
}
Add the "lesson" property to it by overriding the method
class Student: Person {
var lesson: String
/// rewrite
///
/// - Parameters:
/// - name: The name
/// - age: age
override init(name: String, age: Int) {
lesson = "Python" // Must be on super.init() before
super.init(name: name, age: age)
}
}
/// Overrides the instantiated object
let s = Student(name: "Joyce", age: 18)
print(s.lesson) // Python
Add the "lesson" property to it by overloading the method
class Student: Person {
var lesson: String
/// overloading
///
/// - Parameters:
/// - name: The name
/// - age: age
/// - lesson: course
init(name: String, age: Int, lesson:String) {
self.lesson = lesson
super.init(name: name, age: age)
}
}
/// Overloading the instantiated object
let s1 = Student(name: " The handsome boy ", age: 21, lesson: "HTML 5")
print(s1.lesson) // HTML 5
Conclusion:
By overloading, you can quickly add new properties to a method that can be passed in externally
Override, can only set the properties inside the method, the external can't see the parameter list of the class directly