SWIFT中用Switch case 類類型

來源:互聯網
上載者:User

標籤:

有時覺得SWIFT的文法真的強大而又變態,不說了,直接上代碼瞅瞅:

首先先定義一個交通工具的父類

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{//類似於其它程式設計語言的解構函式,退出時釋放對象

        self.wheels = nil

        self.speed = nil

    }

}

建立一個單車類

class Bike : Vehicle{

        init(){

        super.init(wheels: 2, speed: 10)

    }

}

 建立一個小車類及一個加油的方法

class Car : Vehicle{

    init(){

        super.init(wheels: 4, speed: 100.5)

    }

    func addOil(){

        println("The Car is adding oil")

    }

}

 

建立一個貨車類及添加貨物的方法

class Truck : Vehicle{

    init(){

        super.init(wheels: 4, speed:80.5)

    }

    func addCargo(){

        println("The Car is adding cargo")

    }

}

 

var myvehicle:Vehicle = Car()

判斷如果是小車類型的

if (myvehicle is Car){

  println("This is a car")

}

switch myvehicle{

case let bike as Bike: //此時,如果myvehicle是Bike對象那邊將myvehicle賦值給bike變數。下面的代碼也類似

    bike.run()

case let car as Car where car.speed == 100.5: //如果是Car並且速度是100.5,這文法真的很變態

    car.addOil() //調用自有方法

    car.run()

case let truck as Truck:

    truck.addCargo()//調用自有方法

default:

    println("unknow")

}

 

SWIFT中用Switch case 類類型

相關文章

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.