【问题标题】:Argument type 'Spot.Restriction.Type' does not conform to expected type '_FormatSpecifiable'参数类型“Spot.Restriction.Type”不符合预期类型“_FormatSpecifiable”
【发布时间】:2020-03-20 17:49:19
【问题描述】:

我已经尝试了几个小时来寻找答案,但没有找到与我的情况足够接近的答案来翻译它。我正在尝试创建一个程序来从 .json 文件中提取一个数组并读取它,以便我可以过滤答案。感谢您能给我的任何见解或帮助。`

import SwiftUI
import Foundation

struct Spot{

    enum Restriction: String {
        case breakfast, lunch, dinner
    }
    let restrictions: Set<Restriction>
}

extension Spot {
    init?(json: [String: Any]) {
        guard let restrictionsJSON = json["menu"] as? [String]
        else {
            return nil
        }

        var restrictions: Set<Restriction> = []
        for string in restrictionsJSON {
            guard let restriction = Restriction(rawValue: string) else {
                return nil
            }

            restrictions.insert(restriction)
        }

        self.restrictions = restrictions
    }
}

struct Filters: View {

    let filtersort = Spot.Restriction.self
    @State var showGreeting = false

    var body: some View {
        Form {
            Toggle(isOn: $showGreeting){
                Text("Show Welcome Message")
            }.padding()

            if showGreeting {
                Text("\(filtersort)")

            }
        }
    }
}

`

这是我更新后的代码,错误消息与以前相同。

    import SwiftUI
import Foundation

struct Spot: Decodable{

    var restrictions: [String: String]

    enum Restriction: String, CodingKey {
        case timeofyear
    }
}

extension Spot {
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: Restriction.self)
        _ = try values.decode(Double.self, forKey: .timeofyear)
    }
}

struct Filters: View {

    let filtersort = Spot.Restriction.timeofyear
    @State var showGreeting = false

    var body: some View {
        Form {
            Toggle(isOn: $showGreeting){
                Text("Show Welcome Message")
            }.padding()

            if showGreeting {
                Text("\(filtersort)") //Argument type 'Spot.Restriction' does not conform to expected type '_FormatSpecifiable'

            }
        }
    }
}

【问题讨论】:

  • 您应该探索Codable。使用 [String: Any] 现在已经过时了。
  • 感谢您的帮助。我重写了我的代码,但我仍然有同样的错误。知道为什么该错误仍然存​​在吗?
  • Spot.Restriction.selfSpot.Restriction.timeofyear 完全不同。我不知道你真正想要什么。

标签: arrays swift filter enums package.json


【解决方案1】:

Xcode 11.4 提供了您需要的修复。

Text(filtersort.rawValue)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多