我试图在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()

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

最佳答案

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

10-07 20:40