简体   繁体   English

Swift-实例“无法用'...”构造为“静态”方法

[英]Swift - Instance “not constructible with '…” from “static” method

When I try to instantiate a class through "static" method (required from protocol), the compiler don't recognize the initializer, although I pass correct parameters. 当我尝试通过“静态”方法(协议要求)实例化类时,尽管我传递了正确的参数,但编译器无法识别初始化程序。

在此处输入图片说明

在此处输入图片说明

The problem is that you are defining a template called "Comment" in your method declaration that is obscuring the real Comment class. 问题是您在方法声明中定义了一个名为“ Comment”的模板,该模板掩盖了真正的Comment类。 You need to give that template argument a different name. 您需要为该模板参数指定其他名称。

And I believe your JSONSerializable protocol is not defined the way you want it. 而且我相信您的JSONSerializable协议并未按照您想要的方式进行定义。 You can use Self in a protocol to refer to the class implementing the protocol so there is no need for a template. 您可以在协议中使用Self来引用实现该协议的类,因此不需要模板。 Your protocol could look like this: 您的协议可能如下所示:

protocol JSONSerializable {
    class func instanceFrom(json: [String:AnyObject]) -> Self;
}

Then you would implement this method in your Comment class: 然后,您可以在Comment类中实现此方法:

class Comment: JSONSerializable {
    ...

    class func instanceFrom(json: [String:AnyObject]) -> Comment {
        return Comment(message: "lorem lorem", author: User())
    }
}

However, it is preferred in Swift to use initializers instead of class methods: 但是,在Swift中最好使用初始化器而不是类方法:

protocol JSONSerializable {
    init(json: [String:AnyObject])
}

class Comment: JSONSerializable {
    ...

    init(json: [String : AnyObject]) {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM