Swift-类型'(String,JSON)'不符合'StringProtocol';只有struct / enum / class类型可以符合协议

时间:2020-06-22 17:48:18

标签: swift swifty-json

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

但是我还没走那么远。我的if语句出现错误。

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

data.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()
    
}

1 个答案:

答案 0 :(得分:0)

您可以修改相关行,例如:

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

或者您可以直接访问;

data["date"].stringValue == selectedDate