Swift 用实例方法扩展类

Swift 用实例方法扩展类,swift,Swift,我正在尝试扩展Swift中现有类型的功能。我想使用点语法来调用类型上的方法 我想说: existingType.example.someMethod() existingType.example.anotherMethod() 我目前使用的扩展如下: extension ExistingType { func someMethod() { } func anotherMethod() { } } existingType.someMethod() existi

我正在尝试扩展Swift中现有类型的功能。我想使用点语法来调用类型上的方法

我想说:

existingType.example.someMethod()
existingType.example.anotherMethod()
我目前使用的扩展如下:

extension ExistingType {
    func someMethod() {
    }
    func anotherMethod() {
    }
}

existingType.someMethod()
existingType.anotherMethod()
这样做会暴露太多的函数。因此,我想在一个类中编写这些方法,并扩展现有类型以使用该类的实例。我不确定该怎么做

如果我实际实现现有类型,我将执行以下操作:

struct ExistingType {

    var example = Example()
}

struct Example {
    func someMethod() {
    }

    func anotherMethod() {
    }
}
允许我通过以下方式调用这些方法:

let existingType = ExistingType()
existingType.example.someMethod()

问题是我没有实现该类型,因为它已经存在。我只需要扩展它。

您可以创建一个新的
结构

struct NewType {
    let existingType: ExistingType

    func someMethod() {
    }

    func anotherMethod() {
    }
}

看起来您正在尝试添加另一个属性
example
现有类
ExistingType
,并调用该属性的方法。但是,不能在扩展中添加属性。向现有类中添加另一个属性的唯一方法是对其进行子类化。

您能否给出一个使用实际有意义的类和方法的示例,也许这样我们可以了解您正在尝试做的事情。