Sometimes it seems that Swift's grammar is really powerful and perverted, not to mention, directly on the code:
First, define a vehicle's parent class.
Class vehicle{
var wheels:int!
var speed:double!
Init (wheels:int,speed:double) {
Self.speed = Speed
Self.wheels = Wheels
}
Func run () {
println ("The \ (Self.wheels) wheels is running as \ (self.speed) Speed")
}
deinit{//a destructor similar to other programming languages, releasing objects when exiting
Self.wheels = Nil
Self.speed = Nil
}
}
Create a Bike Class
Class bike:vehicle{
Init () {
Super.init (Wheels:2, Speed:10)
}
}
Create a trolley class and a way to refuel
Class car:vehicle{
Init () {
Super.init (Wheels:4, speed:100.5)
}
Func Addoil () {
println ("The Car is adding oil")
}
}
How to create a truck class and add goods
Class truck:vehicle{
Init () {
Super.init (Wheels:4, speed:80.5)
}
Func Addcargo () {
println ("The Car is adding cargo")
}
}
var myvehicle:vehicle = Car ()
Judging if it's a car type,
if (Myvehicle is Car) {
println ("This is a car")
}
Switch myvehicle{
Case let bike as bike://At this point, if Myvehicle is the bike object, assign myvehicle to the bike variable. The following code is similar
Bike.run ()
Case let car as car where car.speed = = 100.5://If it is car and speed is 100.5, this grammar is really perverted
Car.addoil ()//Call your own method
Car.run ()
Case let truck as truck:
Truck.addcargo ()//Call your own method
Default
println ("Unknow")
}
Use the switch case class type in Swift