我的代码结构如下
protocol SomeProtocol { ... } // There Could potentially be unlimited different versions of "SomeClass" that implements "SomeProtocol" class SomeClass : SomeProtocol { ... } extension SomeProtocol { var computedProperty1: Type? { get { getData(SOME_ENUM) } set { validateAndSave(newValue,atKey: SOME_ENUM) } } var computedProperty2: Type? { get { getData(SOME_OTHER_ENUM) } set { validateAndSave(newValue,atKey: SOME_OTEHR_ENUM) } } ... func getData(atKey: ENUM_TYPE) -> Type? { [NEED SOME WAY TO GET THE SAVED DATA AND RETURN IT] } func validateAndSave(value: Type?,atKey: ENUM_TYPE) { [NEED SOME WAY TO SAVE DATA FOR LATER RETURNING] } } // The properties needs to be visible to the client code like this: class ClientCode { let someClassObject: SomeProtocol = SomeClass() someClassObject.computedProperty1 = Type() print(someClassObject.computedProperty1) }
(上面的代码显示了将数据存储在不同字典中的迹象,这是我的第一个想法)
问题是扩展不支持存储的属性.但是,我在哪里/如何存储提交给计算属性的数据呢?
我可以想到两种不同的解决方案,但它们都不好……
>我可以将扩展转换为实现SomeProtocol的类,然后使SomeClass成为它的子类.这将允许我将数据保存在存储的属性中.但是它还需要我实现协议在新类中所需的所有方法 – 这绝对没有意义,因为SomeClass的不同版本应该提供不同的功能.
>我可以放弃整个扩展的想法,并将所有属性移动到SomeProtocol中.但这需要我在具有相同功能的SomeClass的所有不同版本中实现所有计算属性,并且我的扩展想法的重点是避免一遍又一遍地为相同的属性编写相同的实现.
是否有一些我忽略的完全简单的逻辑解决方案?
…或者在我不知道的协议扩展中保存数据的好方法?
…或获得所需功能的其他方式?
…或者我应该把它吸干并使用我不那么漂亮的解决方案之一?
解决方法
有时我们会这么想,以至于我们忽略了一种盯着我们的实际解决方案.
Since all these classes should have the same computed properties,and
since the properties should behave identically in de different
classes…
… 但后来
The problem is that an extension does not support stored properties.
But where/how do I store the data submitted to the computed properties
then?
2.假设它是您想要的一组存储属性,您实际上自己提供了解决方案!做了一个现在有意义的改变.
I Could transform the extension into a class
that implementsinstead,and then make SomeClass a subclass of it. That
SomeProtocol
would allow me to save the data in stored properties.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。