有光泽的iOS不符合协议

时间:2016-02-04 12:17:30

标签: ios json swift

我正在尝试集成Gloss来进行json解析,但是我得到了很多非意义错误。

我安装了pod安装它,我经历了以下事项:

  • 首先,当我导入它时,我得到了 :Cannot import underlying modules glossy,我不知道如何,但是在github repo中复制粘贴GlossExample项目中的示例后,它就消失了。

  • 第二,如果我使用:struct Repo: Glossy我收到错误Repo doesn't conform to protocols Decodable and Encodable,但代码是从示例中粘贴的,并且存在方法init?(json: JSON)func toJSON() -> JSON? < / p>

  • 然后我尝试使用struct Repo: Decodable并将此功能用于解码器:

    init?(json: JSON) {
    let repoId: Int = "id" <~~ json
    

我收到以下错误: 35: Binary operator '<~~' cannot be applied to operands of type 'String' and 'JSON'

  • 最后我说好了,我不会使用重载运算符,而是正常的Decoder类:

    init?(json: JSON) {
      self.repoId = Decoder.decodeURL("id")(json)
    }
    

我得到了: Cannot convert value of type 'JSON' to expected argument type 'JSON' (aka 'Dictionary<String, AnyObject>')

欢迎您提供帮助和解答!

1 个答案:

答案 0 :(得分:1)

  
      
  • 首先,当我导入它时,我得到:Cannot import underlying modules glossy,我不知道如何,但是在github repo中复制粘贴GlossExample项目中的示例后,它就消失了。
  •   

这是一个在Xcode中发生的问题,有一些框架,但只是清理代码或直接运行它通常会消除警告。否则,它可能与使用较旧版本的Xcode有关。

  

如果我使用{h> struct Repo: Glossy,我会收到错误Repo doesn't conform to protocols Decodable and Encodable,但代码是从示例中粘贴的,并且存在方法init?(json: JSON)func toJSON() -> JSON?

这意味着您的struct不符合这两种协议。来自Glossy declaration

/**
Convenience protocol for objects that can be
translated from and to JSON
*/
public protocol Glossy: Decodable, Encodable { }

因此,Glossy协议继承了Decodable和Encodable,这意味着您需要为两个协议实现协议功能,而不仅仅是toJSON() -> JSON?

  

然后我尝试使用struct Repo: Decodable并将此功能用于解码器:...

您需要首先在结构中声明常量,并在init中反序列化JSON并将值设置为常量:

struct Repo: Decodable {
    let repoId: Int

    init?(json: JSON) {
        guard let repoId: Int = "id" <~~ json { else return nil }

        self.repoId = repoId
    }
}
相关问题