簡體   English   中英

Swift - 類型“(字符串,JSON)”不能符合“字符串協議”; 只有結構/枚舉/類類型可以符合協議

[英]Swift - Type '(String, JSON)' cannot conform to 'StringProtocol'; only struct/enum/class types can conform to protocols

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

但我什至還沒有走到那一步。 我的if語句出現錯誤。

我收到的錯誤說Type '(String, JSON)' cannot conform to 'StringProtocol'; only struct/enum/class types can conform to protocols 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()
    
}

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

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

或者你可以直接訪問like;

data["date"].stringValue == selectedDate

暫無
暫無

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

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