Swift中的自定义类集群 [英] Custom class clusters in Swift
问题描述
这是一个相对常见的设计模式:
This is a relatively common design pattern:
http:// stackoverflow.com/a/17015041/743957
它允许您从您的 init返回一个子类
电话。
我试图找出使用Swift实现同样事情的最佳方法。
I'm trying to figure out the best method of achieving the same thing using Swift.
我知道很有可能有一个更好的方法来实现与Swift相同的事情。但是,我的课程将由现有的Obj-C库进行初始化,我无法控制。所以它需要这样工作,可以从Obj-C调用。
I do know that it is very likely that there is a better method of achieving the same thing with Swift. However, my class is going to be initialized by an existing Obj-C library which I don't have control over. So it does need to work this way and be callable from Obj-C.
任何指针都将非常感谢。
Any pointers would be very much appreciated.
推荐答案
我不相信Swift可以直接支持这种模式,因为初始化程序不会像在Objective C中返回一个值 - 所以你没有机会返回一个替代对象实例。
I don't believe that this pattern can be directly supported in Swift, because initialisers do not return a value as they do in Objective C - so you do not get an opportunity to return an alternate object instance.
您可以使用类型方法作为对象工厂 - 一个相当有创意的示例是 -
You can use a type method as an object factory - a fairly contrived example is -
class Vehicle
{
var wheels: Int? {
get {
return nil
}
}
class func vehicleFactory(wheels:Int) -> Vehicle
{
var retVal:Vehicle
if (wheels == 4) {
retVal=Car()
}
else if (wheels == 18) {
retVal=Truck()
}
else {
retVal=Vehicle()
}
return retVal
}
}
class Car:Vehicle
{
override var wheels: Int {
get {
return 4
}
}
}
class Truck:Vehicle
{
override var wheels: Int {
get {
return 18
}
}
}
main.swift
main.swift
let c=Vehicle.vehicleFactory(4) // c is a Car
println(c.wheels) // outputs 4
let t=Vehicle.vehicleFactory(18) // t is a truck
println(t.wheels) // outputs 18
这篇关于Swift中的自定义类集群的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!