如何在swift初始化器中确定Self类

时间:2016-08-18 22:27:02

标签: swift

在父类的便利初始值设定项中,如何在调用self.init()之前确定当前类?

public class Vehicle {

    public convenience init( withDictionary rawData: [String:AnyObject] ) {

        // how do I determine whether this is a Car here?

        self.init()

    }

}

public class Car: Vehicle {

}

public class Bike: Vehicle {

}

2 个答案:

答案 0 :(得分:0)

似乎允许使用self.dynamicType

public class Vehicle {

    public convenience init( withDictionary rawData: [String:AnyObject] ) {

        let myType = self.dynamicType

        print( "This is a \(myType)" )

        self.init()

    }

}

public class Car: Vehicle {

}

public class Bike: Vehicle {

}

let car = Car( withDictionary: ["key":"value"] )

// prints "This is a Car"

答案 1 :(得分:0)

您需要使用" is"运算符来确定类的类型。

public class Vehicle 
{

  public convenience init( withDictionary rawData: [String:AnyObject] ) 
  {

    self.init()

    if self is Car
    {
      print("It's a car")
    }
    else if self is Bike
    {
      print("It's a bike")
    }

  }
}

但是,你也可以在Car或Bike的init函数中进行初始化。