0

我正在尝试为执行相同操作的不同类型对象概括一个函数(使用 keyPath 从对象中检索一个值)。

class GenericOutputParameter<Type>: Equatable    {

    // Single Line Parameter for the Deal parameters


    var path: WritableKeyPathApplicator<Type>
    var label: String
    var value: Any?         // THIS IS OPTIONAL
    var format: Int
    var columnID: String
    var order: Int

    init(path: WritableKeyPathApplicator<Type>, label: String, value: Any?, format: Int, order: Int, columnID: String)  {

        self.path = path
        self.label = label
        self.value = value
        self.format = format
        self.order = order
        self.columnID = columnID
    }
 }

protocol haveOutputs {

    associatedtype containerType

    var dictionary: [String : (path: WritableKeyPathApplicator<containerType>,label: String, value: Any, format: Int, order: Int)] { get set }
    var outputs: [GenericOutputParameter<containerType>] { get set }

    }



func fillOutputs<T: haveOutputs>(container: inout T)   {

    container.outputs.removeAll()

    for (columnID, valueTuple) in container.dictionary {

        container.outputs.append(GenericOutputParameter(path: valueTuple.path, label: valueTuple.label, value: valueTuple.path.retrieve(from: container), format: valueTuple.format,order: valueTuple.order, columnID: columnID))
        }


    container.outputs.sort(by: { $0.order < $1.order })

    }   // END OF FILLOUTPUTS

我在协议中使用了 associatedType,因为每个对象都有自己不同的字典。

函数 fillOutputs(container: inout T) 从对象中检索由键路径指定的参数的值并将其附加到数组中。

我在代码末尾的 container.outputs.append 行中收到错误,如下所示:无法使用类型为“(来自:T)”的参数列表调用“检索”。这是指检索(来自:容器)。在尝试概括之前,此函数是每个对象(容器)的方法,并且使用retrieve(from: self) 有效。

作为参考,retrieve 方法是另一个通用函数的一部分:

class WritableKeyPathApplicator<Type> {

    private let applicator: (Type, Any) -> Type
    private let retriever: (Type) -> Any

    init<ValueType>(_ keyPath: WritableKeyPath<Type, ValueType>) {

        applicator = {

            ...

            }


        retriever = {
            ...

            }

        }


    func apply(value: Any, to: Type) -> Type {
        return applicator(to, value)
        }


    func retrieve(from: Type)   -> Any  {
        return retriever(from)
        }

}

鉴于我不是 Swift 专家,也不是完全理解协议,我可能迷失在一杯水中,我将不胜感激任何想法/帮助。谢谢

4

0 回答 0