簡體   English   中英

SwiftUI-類型“服務”不符合協議“可解碼”

[英]SwiftUI - Type 'Service' does not conform to protocol 'Decodable'

我正在構建的一個小應用程序上正在使用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'

Codable不能具有Any ,加上businessLocation是一個字典,而不是一個數組,因此Replace

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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM