2017-05-12 11 views
0

CarViewControllerは車のプロパティでCarを受け取るだけであることをコンパイラによって保証したいと思います。Swiftのメソッドやプロパティをオーバーライドするときの多態性

を考えると、次のSWIFTコード例:

class Vehicle { 
    func doSomething(){} 
} 

class Car: Vehicle { 
    func doCarThings(){} 
} 

class VehicleViewController<T:Vehicle> : UIViewController { 
    var vehicle : T!; 

    override func viewDidLoad() { 
     super.viewDidLoad(); 
     vehicle.doSomething(); 
    } 
} 

class CarViewController:VehicleViewController<Car> { 
    override func viewDidLoad() { 
     super.viewDidLoad(); 
     vehicle.doCarThings(); 
    } 
} 

それは正しいが、使用している:私は、ジェネリックベースのアプローチを試みたCannot override mutable property 'vehicle' of type 'Vehicle!' with covariant type 'Car!'

:私は次のエラーを取得する

class Vehicle { 
    func doSomething(){} 
} 

class Car: Vehicle { 
    func doCarThings(){} 
} 

class VehicleViewController : UIViewController { 
    var vehicle : Vehicle!; 

    override func viewDidLoad() { 
     super.viewDidLoad(); 
     vehicle.doSomething(); 
    } 
} 

class CarViewController:VehicleViewController { 
    var vehicle: Car! 

    override func viewDidLoad() { 
     super.viewDidLoad(); 
     vehicle.doCarThings(); 
    } 
} 

ストーリーボードのクラスのジェネリックスはエラーになります(なぜなら、それらは目的に合わせてコンパイルされるからです)。

ジェネリックを使用せずにどうすればいいですか?

ありがとうございます!

+0

可能Dublicate http://stackoverflow.com/questions/24094158/overriding-superclass-property-with-different-type-in​​-swift –

答えて

0

私はここで本当にデザインについてはよく分からないんだけど、あなたはあなたができる望むものを達成するために:

class CarViewController: VehicleViewController { 
    var vehicleAsCar: Car { return self.vehicle as! Car } 

    override func viewDidLoad() { 
     super.viewDidLoad(); 
     vehicleAsCar.doCarThings(); 
    } 
} 

しかし、これは非常に臭いと思われます。より安全な夜のこと: の

class CarViewController: VehicleViewController { 
    override var vehicle: Vehicle! { 
     didSet { 
      assert(vehicle is Car, "Attempt to set vehicle to non-Car") 
     } 
    } 
    var vehicleAsCar: Car { return self.vehicle as! Car } 

    override func viewDidLoad() { 
     super.viewDidLoad(); 
     vehicleAsCar.doCarThings(); 
    } 
} 
0

hereから撮影:

をあなたがそれを行う傾けるよう

You can provide a custom getter (and setter, if appropriate) to override any inherited property, regardless of whether the inherited property is implemented as a stored or computed property at source. The stored or computed nature of an inherited property is not known by a subclass—it only knows that the inherited property has a certain name and type. You must always state both the name and the type of the property you are overriding, to enable the compiler to check that your override matches a superclass property with the same name and type.

はそうプロパティGetterおよびSetterのオーバーライド。

関連する問題