SwiftUI - 类型“服务”不符合协议“可解码”

Posted

技术标签:

【中文标题】SwiftUI - 类型“服务”不符合协议“可解码”【英文标题】:SwiftUI - Type 'Service' does not conform to protocol 'Decodable' 【发布时间】:2019-07-18 12:35:53 【问题描述】:

我在我正在构建的一个小应用程序上使用 SwiftUI,但我遇到了 Codable 的问题并且我遇到了一些错误。

我有一个如下所示的 JSON 文件

[
    
        "id": "",
        "name": "services",
        "items": [
            
                "id": 0
                "businessName": "Some Name",
                "businessTelephone": "01234567890",
                "businessEmail": "email@gmail.com",
                "businessWebsite": "website.com",
                "businessLocation":  "latitude": "54.137256", "longitude": "-1.524727" ,
                "travelLimit": 50,
                "description": "A description about some business",
                "categories": ["Category 1"]
            
    
]

我有一个看起来像这样的结构

struct Service: Hashable, Codable, Identifiable  

    var id: Int
    var businessName: String
    var businessTelephone: String
    var businessEmail: String
    var businessWebsite: String
    var businessLocation: Array<Any>
    var travelLimit: Int
    var description: String
    var categories: [Category]

    enum Category: String, CaseIterable, Hashable, Codable 

        case category1 = "Category 1"
        case category2 = "Category 2"

    


但是,我收到以下错误

Type 'Service' does not conform to protocol 'Decodable'
Type 'Service' does not conform to protocol 'Encodable'
Type 'Service' does not conform to protocol 'Equatable'
Type 'Service' does not conform to protocol 'Hashable'

【问题讨论】:

【参考方案1】:

Codable 不能有 Any ,加上 businessLocation 是字典而不是数组,所以替换

var businessLocation: Array<Any>

var businessLocation:[String:String]

模型

// MARK: - Element
struct Root: Codable 
    let id, name: String
    let items: [Item]


// MARK: - Item
struct Service: Codable 
    let id: Int
    let businessName, businessTelephone, businessEmail, businessWebsite: String
    let businessLocation: BusinessLocation
    let travelLimit: Int
    let itemDescription: String
    let categories: [String]

    enum CodingKeys: String, CodingKey 
        case id, businessName, businessTelephone, businessEmail, businessWebsite, businessLocation, travelLimit
        case itemDescription = "description"
        case categories
    


// MARK: - BusinessLocation
struct BusinessLocation: Codable 
    let latitude, longitude: String

解码

do 
    let res = try JSONDecoder().decode([Root].self, from: data)
    print(res)

catch 
    print(error)

【讨论】:

以上是关于SwiftUI - 类型“服务”不符合协议“可解码”的主要内容,如果未能解决你的问题,请参考以下文章

字符串字典:任何不符合协议“可解码”[重复]

Text 或 Image 等视图类型如何符合 SwiftUI 中的 View 协议?

类型“ContentView”不符合协议“View”(Xcode - Swift UI)

不符合协议 Decodabel 和 Encodable

如何在 SwiftUI 中符合 ButtonStyle 协议?

类型“Favorites.Type”不能符合“Encodable”;只有结构/枚举/类类型可以符合协议