Swift:如何在库中的基类中构建属性

问题描述 投票:0回答:1

我需要在库中构建一个基类,但是库不知道这个属性。在这种情况下,我如何构建基类。 这是代码示例:

///Code in the library
open class BaseClass {
    // the problem is here. how I can set up such a property in the base class 
    // where the type of the property is not available in the base class.
    public var property: ThePropertyTypeThatThatLibraryDonotKnow 

    init(property: ThePropertyTypeThatThatLibraryDonotKnow)
}
///CodeIn the main app
class ThePropertyTypeThatThatLibraryDonotKnow {
     var someProperty: Int
}

///Usage of the BaseClass

/// 1 use the BaseClass directly
let property = ThePropertyTypeThatThatLibraryDonotKnow()
let object = BaseClass(property: property)

/// 2 subclass the BaseClass.
class SubClass: BaseClass {}
let property = ThePropertyTypeThatThatLibraryDonotKnow()
let object = SubClass(property: property)

有没有办法可以声明

property
基类。

swift
1个回答
0
投票

有多种方法可以解决这个问题,但我可能采取的方法是使你的基类通用。

open class BaseClass<T> {
    public var prop: T

    public init(prop: T) {
        self.prop = prop
    }
}

现在在您的应用程序中,您可以创建通用基类的专用子类:

struct InternalType {
    let value: Int
}

final class SubClass: BaseClass<InternalType> {}
let instance = SubClass(prop: InternalType(value: 99))
print(instance.prop) //prints InternalType(value:99)
print(instance.prop.value) //prints 99

为了使泛型类型在子类中更有用,您可能需要定义一个协议并将泛型类型约束到它。

//Library
public protocol HasIntValue {
    var value: Int { get }
}

//Updated definition of BaseClass
open class BaseClass<T: HasIntValue> { ... }

//App
extension InternalType: HasIntValue {}
extension SubClass {
    func add(other: T) -> Int {
        return prop.value + other.value
    }
}

我建议阅读 Swift 的泛型类型。 Swift 编程语言是一个很好的起点:https://docs.swift.org/swift-book/documentation/the-swift-programming-language/generics/#Generic-Types

© www.soinside.com 2019 - 2024. All rights reserved.