Swift:如何在库的基类中声明未知类型的属性
解决Swift库中类型未知属性的基类构建问题
针对库中无法知晓属性具体类型的场景,有三种可行方案,其中泛型基类是最推荐的类型安全实现方式,以下是具体说明:
方案一:泛型基类(推荐)
通过泛型参数在基类中占位未知类型,主应用使用时指定具体类型,既保证类型安全,又不破坏库的封装性。
库中的代码
open class BaseClass<PropertyType> { public var property: PropertyType public init(property: PropertyType) { self.property = property } }
主应用中的代码
class ThePropertyTypeThatLibraryDoesNotKnow { var someProperty: Int = 0 }
使用方式
1. 直接使用BaseClass
let property = ThePropertyTypeThatLibraryDoesNotKnow() let object = BaseClass(property: property) // 此时object的类型为BaseClass<ThePropertyTypeThatLibraryDoesNotKnow>
2. 子类化BaseClass
如果需要固定子类的属性类型:
class SubClass: BaseClass<ThePropertyTypeThatLibraryDoesNotKnow> {} let property = ThePropertyTypeThatLibraryDoesNotKnow() let object = SubClass(property: property)
如果希望子类保留泛型灵活性:
class GenericSubClass<T>: BaseClass<T> {} let property = ThePropertyTypeThatLibraryDoesNotKnow() let object = GenericSubClass(property: property)
方案二:协议抽象(适合需要约束行为的场景)
在库中定义协议约束未知类型的行为,主应用让具体类型遵守协议,基类中使用协议类型作为属性类型。
库中的代码
// 定义协议,约束类型必须实现的行为 public protocol PropertyProtocol { func performAction() } open class BaseClass { public var property: PropertyProtocol public init(property: PropertyProtocol) { self.property = property } }
主应用中的代码
class ThePropertyTypeThatLibraryDoesNotKnow: PropertyProtocol { var someProperty: Int = 0 func performAction() { print("执行预设操作") } }
使用方式
与泛型方案的使用逻辑一致,基类可直接调用property.performAction(),保证类型行为符合预期。
方案三:使用Any(不推荐,类型不安全)
如果不需要类型安全和行为约束,可直接用Any作为属性类型,但会丢失类型信息,使用时需强制转换,易引发运行时错误:
库中的代码
open class BaseClass { public var property: Any public init(property: Any) { self.property = property } }
使用时的问题
let object = BaseClass(property: ThePropertyTypeThatLibraryDoesNotKnow()) // 使用时必须强制转换类型 if let typedProperty = object.property as? ThePropertyTypeThatLibraryDoesNotKnow { typedProperty.someProperty = 10 }
内容的提问来源于stack exchange,提问作者user2823793
相关产品推荐
相关产品推荐

