Swift 中的自定义类集群 [英] Custom class clusters in Swift

查看:26
本文介绍了Swift 中的自定义类集群的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个比较常见的设计模式:

This is a relatively common design pattern:

https://stackoverflow.com/a/17015041/743957

它允许您从 init 调用中返回一个子类.

It allows you to return a subclass from your init calls.

我正在尝试找出使用 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.

非常感谢任何指点.

推荐答案

我不相信这种模式可以在 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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆