Swift Inheritance and extension

Source: Internet
Author: User

Inherit & extension inheritance and extension

Parent class

Class Car {

var speed = 0

var Description: String {

Return "mph" (speed) km/h

}

Func sound () {

}

}

Let a car = car ()

A car. Description

Subclass Inherits Parent Class

Class Bike: Car {

var has basket = False

}

Let a bike = bicycle ()

A bike. There is a basket = True

a bike. Speed = 25

A bike. Description

Subclasses of subclasses

Class couple bike: Bike {

var current number of passengers = 0

}

Let a couple bike = couple bike ()

A couple bike. Speed = 20

A couple bike. Description

Methods for subclasses overloading parent classes

Class bullet train: Car {

Override Func beep () {

println ("Toot Toot")

}

}

Let a bullet train = car ()

A bullet train. Sound ()

The subclass overloads the computed properties of the parent class

Class Car: Car {

Override var speed = 60

Number of var wheels = 0

Override var Description: string{

Return super. Description + ", have \ (number of wheels) of wheels"

}

Override var speed: int{

Didset {

If speed > 120 {

println ("Warning: You are speeding")

}

}

}

}

Let a car = car ()

A car. Speed = 121

A car. Number of wheels = 4

A car. Description

Extension (equivalent to classification)

The class/struct/enum type that already exists. Typically used to

1. Source code agnostic situation

2. Decomposition of complex classes to improve maintainability

Extension Double {

var rmb:double{

return self * 0.0597

}

}

31_4150.rmb

Integer self squared

Extension Int {

mutating func squared () {

Self *= Self

}

}

var an integer = 1024

An integer. Square ()

An integer

Swift Inheritance and extension

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.