有时觉得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")

}