【问题标题】:Swift - Type '(String, JSON)' cannot conform to 'StringProtocol'; only struct/enum/class types can conform to protocolsSwift - 类型 '(String, JSON)' 不能符合 'StringProtocol';只有结构/枚举/类类型可以符合协议
【发布时间】:2020-10-12 16:09:03
【问题描述】:

我正在使用 SwiftyJSON。最终我想看看"date"的值是否等于selectedDate的值,如果是,打印"event"的值。

但我还没走到那一步。我的if 声明出现错误。

我收到的错误是Type '(String, JSON)' cannot conform to 'StringProtocol'; only struct/enum/class types can conform to protocols

数据.json

[
 {
      "date": "01.01",
      "event": "Mom birthday",
     
  },
]

ViewController.swift

var json:JSON = false    
var selectedDate:String = "01.01"

func updateView() {
    
    json.forEach { (key, data) in
        if key == "date", data.stringValue == selectedDate {
            print("found it!")
        } else {
            print("no matches")
        }
    }
    
}

覆盖 func viewDidLoad() { super.viewDidLoad()

    // Get JSON data
    if let path = Bundle.main.path(forResource: "Devotions", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
            json = try JSON(data: data)
        } catch let error {
            print("parse error: \(error.localizedDescription)")
        }
    } else {
        print("Invalid filename/path.")
    }
    
    updateView()
    
}

【问题讨论】:

    标签: swift swifty-json


    【解决方案1】:

    您可以修改相关行,如:

    data.forEach { (key, data) in
        if key == "date", data.stringValue == selectedDate {
            print("found it!")
        }
    }
    

    或者你可以直接访问喜欢;

    data["date"].stringValue == selectedDate
    

    【讨论】:

    • 这也不起作用。我添加了一个else 语句,它正在返回该结果,所以我猜if 条件没有得到满足。我会用更多细节更新我上面的代码,因为它们可能是相关的。
    • 您指定的编译错误应该已修复。下一步你可以调试json值data是否包含“日期”。
    猜你喜欢
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多