Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在类层次结构中应用Swift泛型/协议?_Swift_Oop_Generics_Protocols - Fatal编程技术网

如何在类层次结构中应用Swift泛型/协议?

如何在类层次结构中应用Swift泛型/协议?,swift,oop,generics,protocols,Swift,Oop,Generics,Protocols,让我们从我要解决的问题开始。我正在将XML文档解析为模型对象的层次结构。所有模型对象都有一个具有一组公共属性的公共基类。然后,每个特定的模型类都有一些附加属性 以下是几个模型类的简化示例: class Base { var id: String? var name: String? var children = [Base]() } class General: Base { var thing: String? } class Specific: Gener

让我们从我要解决的问题开始。我正在将XML文档解析为模型对象的层次结构。所有模型对象都有一个具有一组公共属性的公共基类。然后,每个特定的模型类都有一些附加属性

以下是几个模型类的简化示例:

class Base {
    var id: String?
    var name: String?
    var children = [Base]()
}

class General: Base {
    var thing: String?
}

class Specific: General {
    var boring: String?
}

class Other: Base {
    var something: String?
    var another: String?
}
我遇到的问题是实现一种干净的方法来编写XML解析器类来处理这个模型层次结构。我正在尝试编写与模型层次结构匹配的解析器层次结构。以下是我的尝试:

protocol ObjectParser {
    associatedtype ObjectType

    func createObject() -> ObjectType
    func parseAttributes(element: XMLElement, object: ObjectType)
    func parseElement(_ element: XMLElement) -> ObjectType
}

class BaseParser: ObjectParser {
    typealias ObjectType = Base

    var shouldParseChildren: Bool {
        return true
    }

    func createObject() -> Base {
        return Base()
    }

    func parseAttributes(element: XMLElement, object: Base) {
        object.id = element.attribute(forName: "id")?.stringValue
        object.name = element.attribute(forName: "name")?.stringValue
    }

    func parseChildren(_ element: XMLElement, parent: Base) {
        if let children = element.children {
            for child in children {
                if let elem = child as? XMLElement, let name = elem.name {
                    var parser: BaseParser? = nil

                    switch name {
                    case "general":
                        parser = GeneralParser()
                    case "specific":
                        parser = SpecificParser()
                    case "other":
                        parser = OtherParser()
                    default:
                        break
                    }

                    if let parser = parser {
                        let res = parser.parseElement(elem)
                        parent.children.append(res)
                    }
                }
            }
        }
    }

    func parseElement(_ element: XMLElement) -> Base {
        let res = createObject()

        parseAttributes(element: element, object: res)

        if shouldParseChildren {
            parseChildren(element, parent: res)
        }

        return res
    }
}

class GeneralParser: BaseParser {
    typealias ObjectType = General

    override func createObject() -> General {
        return General()
    }

    func parseAttributes(element: XMLElement, object: General) {
        super.parseAttributes(element: element, object: object)

        object.thing = element.attribute(forName: "thing")?.stringValue
    }
}

class SpecificParser: GeneralParser {
    typealias ObjectType = Specific

    override func createObject() -> Specific {
        return Specific()
    }

    func parseAttributes(element: XMLElement, object: Specific) {
        super.parseAttributes(element: element, object: object)

        object.boring = element.attribute(forName: "boring")?.stringValue
    }
}
还有
OtherParser
,它与
GeneralParser
相同,只是将
General
替换为
Other
。当然,在我的层次结构中还有更多的模型对象和相关的解析器

这个版本的代码几乎可以正常工作。您会注意到,
GeneralParser
SpecificParser
类中的
parseAttributes
方法没有
override
。我认为这是由于
对象
参数的类型不同所致。这样做的结果是,不会从
BaseParser
parseElement
方法调用特定于解析器的
parseAttributes
方法。我通过将所有
parseAttributes
签名更新为:

func parseAttributes(element: XMLElement, object: Base)
然后,在非基本解析器中,我必须使用强制转换(并添加
override
,如
GeneralParser
中的以下内容:

override func parseAttributes(element: XMLElement, object: Base) {
    super.parseAttributes(element: element, object: object)

    let general = object as! General
    general.thing = element.attribute(forName: "thing")?.stringValue
}
最后,问题是:

如何消除在
parseAttributes
方法层次结构中强制转换的需要,并利用协议的关联类型?更一般地说,这是解决此问题的正确方法吗?是否有更“快速”的方法来解决此问题

以下是一些基于此简化对象模型的合成XML(如果需要):

<other id="top-level" name="Hi">
    <general thing="whatever">
        <specific boring="yes"/>
        <specific boring="probably"/>
        <other id="mid-level">
            <specific/>
        </other>
    </general>
</other>

以下是我解决此问题的方法:

func createObject(from element: XMLElement) -> Base {
    switch element.name {
    case "base":
        let base = Base()
        initialize(base: base, from: element)
        return base
    case "general":
        let general = General()
        initialize(general: general, from: element)
        return general
    case "specific":
        let specific = Specific()
        initialize(specific: specific, from: element)
        return specific
    case "other":
        let other = Other()
        initialize(other: other, from: element)
        return other
    default:
        fatalError()
    }
}

func initialize(base: Base, from element: XMLElement) {
    base.id = element.attribute(forName: "id")?.stringValue
    base.name = element.attribute(forName: "name")?.stringValue
    base.children = element.children.map { createObject(from: $0) }
}

func initialize(general: General, from element: XMLElement) {
    general.thing = element.attribute(forName: "thing")?.stringValue
    initialize(base: general, from: element)
}

func initialize(specific: Specific, from element: XMLElement) {
    specific.boring = element.attribute(forName: "boring")?.stringValue
    initialize(general: specific, from: element)
}

func initialize(other: Other, from element: XMLElement) {
    other.something = element.attribute(forName: "something")?.stringValue
    other.another = element.attribute(forName: "another")?.stringValue
    initialize(base: other, from: element)
}
我真的不认为需要解析器类的镜像继承层次结构。我最初尝试将
initialize
函数作为扩展中的构造函数,但您不能覆盖扩展方法。当然,您可以将它们作为类本身的
init
方法,但我假设您希望保留XML与型号代码分开的特定代码

--加成--

我仍然很想知道是否有一个更普遍的解决方案 处理调用重载(非重写)的总体问题 Swift中基类中的方法(如parseAttributes)

你可以用与其他语言相同的方式来做。你可以投射对象(如果需要的话),然后调用方法。在这方面,斯威夫特没有什么神奇或特别之处

class Foo {
    func bar(with: Int) {
        print("bar with int called")
    }
}

class SubFoo: Foo {
    func bar(with: String) {
        print("bar with string called")
    }
}


let foo: Foo = SubFoo()

foo.bar(with: 12) // can't access bar(with: Double) here because foo is of type Foo
(foo as? SubFoo)?.bar(with: "hello") // (foo as? SubFoo)? will allow you to call the overload if foo is a SubFoo

let subFoo = SubFoo()

// can call either here
subFoo.bar(with: "hello")
subFoo.bar(with: 12)

下面是我解决这个问题的方法:

func createObject(from element: XMLElement) -> Base {
    switch element.name {
    case "base":
        let base = Base()
        initialize(base: base, from: element)
        return base
    case "general":
        let general = General()
        initialize(general: general, from: element)
        return general
    case "specific":
        let specific = Specific()
        initialize(specific: specific, from: element)
        return specific
    case "other":
        let other = Other()
        initialize(other: other, from: element)
        return other
    default:
        fatalError()
    }
}

func initialize(base: Base, from element: XMLElement) {
    base.id = element.attribute(forName: "id")?.stringValue
    base.name = element.attribute(forName: "name")?.stringValue
    base.children = element.children.map { createObject(from: $0) }
}

func initialize(general: General, from element: XMLElement) {
    general.thing = element.attribute(forName: "thing")?.stringValue
    initialize(base: general, from: element)
}

func initialize(specific: Specific, from element: XMLElement) {
    specific.boring = element.attribute(forName: "boring")?.stringValue
    initialize(general: specific, from: element)
}

func initialize(other: Other, from element: XMLElement) {
    other.something = element.attribute(forName: "something")?.stringValue
    other.another = element.attribute(forName: "another")?.stringValue
    initialize(base: other, from: element)
}
我真的不认为需要解析器类的镜像继承层次结构。我最初尝试将
initialize
函数作为扩展中的构造函数,但您不能覆盖扩展方法。当然,您可以将它们作为类本身的
init
方法,但我假设您希望保留XML与型号代码分开的特定代码

--加成--

我仍然很想知道是否有一个更普遍的解决方案 处理调用重载(非重写)的总体问题 Swift中基类中的方法(如parseAttributes)

你可以用与其他语言相同的方式来做。你可以投射对象(如果需要的话),然后调用方法。在这方面,斯威夫特没有什么神奇或特别之处

class Foo {
    func bar(with: Int) {
        print("bar with int called")
    }
}

class SubFoo: Foo {
    func bar(with: String) {
        print("bar with string called")
    }
}


let foo: Foo = SubFoo()

foo.bar(with: 12) // can't access bar(with: Double) here because foo is of type Foo
(foo as? SubFoo)?.bar(with: "hello") // (foo as? SubFoo)? will allow you to call the overload if foo is a SubFoo

let subFoo = SubFoo()

// can call either here
subFoo.bar(with: "hello")
subFoo.bar(with: 12)

给我们一个
XML
给玩具with@Alexander我在问题的末尾添加了一些XML,但您确实不需要它来提供答案,它们不是从哪里调用的?@courteouselk来自
BaseParser
parseElement
方法。您将解析器作为一个单独的层次结构来编写有什么原因吗?例如,我只需要一个
必需的init(from:xmldecker)
在您的模型类中,让每个类从给定的
XMLDecoder
实例中获取它们的属性值,这将只是一个简单的类型,可以为XML元素的给定属性名提供属性值。然后您只需将此解码器实例传递到模型层次结构中。为我们提供一个
XML
with@Alexander我在问题的末尾添加了一些XML,但您确实不需要它来提供答案,它们不是从哪里调用的?@courteouselk来自
BaseParser
parseElement
方法。您将解析器作为一个单独的层次结构来编写有什么原因吗?例如,我只需要一个
必需的init(from:xmldecker)
在您的模型类中,让每个类从给定的
XMLDecoder
实例获取它们的属性值,这将只是一个简单的类型,可以为XML元素的给定属性名提供属性值。然后,您只需将此解码器实例传递到模型层次结构中。