Use the switch case class type in Swift

Source: Internet
Author: User
Tags switch case

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.