我有一個從遠程服務器獲取并解碼的 JSON 檔案。它被解碼為一個結構,然后在 @Published var 中使用。
例如:
JSON:
[{"keyword": "foo"}, {"keyword": "blah"}]
結構:
struct keywords: Codable {
var keyword: String
}
可觀察類:
@Published var keys: [keywords] = []
我需要使用 if 陳述句對用戶輸入的值進行實時比較,使用 contains。我可以讓它使用鍵 var 中的第一個條目并檢查該字串中可能存在的任何字符,但我無法讓它在整個陣列中僅在完整字串(而不是單個字符)上作業。
以下是僅針對陣列的第一個條目和每個單獨字符正確檢查的內容。
if keys[0].keyword.contains(where: blah.contains)
我也嘗試將它映射到這樣的字串(完全相同):
if (keys[0].keyword.map{String($0)}).contains(where: blah.contains)
一整天都在這里,但找不到任何關于如何正確執行此操作的檔案。
目標不僅是讓它使用陣列的第一個條目,而且是整個陣列的條目。我知道那是 [0] 但沒有它就無法編譯。我需要在整個字串上進行比較,而不是在單個字符上進行比較。
例如,如果單詞 blah 是陣列并且用戶輸入 bla 它不應該匹配任何內容。只有當整個單詞 blah 包含在用戶的條目中時它才應該匹配(即 fooblahfoo 會匹配,因為 blah 在字串中,但 foobalbabh 不會匹配,即使單詞 blah 中包含的所有字符都在該字串中)。
感謝對實際代碼示例的任何幫助。這是 Swift 5.5。
更新:
不確定混亂來自哪里,但這里有一個更清晰的解釋。
有一個名為用戶名的文本欄位,用戶在其中輸入一個字串。
If the user enters the string fooblahfoo and the word blah is somewhere in the array it should match.
This is easy when you have a simple array of strings like this: keywords = ["foo", "blah"]
For that you just do keywords.contains(where: username.contains)
However, the decoded JSON is more of a dictionary than a simple array of strings, so you have to call to the key of keyword and look at all the values in order to make the comparison.
uj5u.com熱心網友回復:
首先,contains(where:)在keys陣列上使用 -- 然后,檢查每個專案以查看用戶輸入是否包含該關鍵字。
struct Keywords: Codable {
var keyword: String
}
var keys: [Keywords] = [.init(keyword: "foo"),.init(keyword: "blah")]
var userInput = "fooblahfoo"
var result = keys.contains { userInput.contains($0.keyword) }
print(result)
真的
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/422001.html
標籤:
