[英]How to compare two string values within a threshold value in swift?
我正在嘗試編寫一個代碼,其中我有兩次 [hh:min] 數據(字符串類型)。 只需要進行比較,但挑戰是我的代碼在返回最終值之前經過了一些驗證。 所以斷言有時會失敗,說明預期值為 [17:04],但實際值為 [17:05]。 有什么方法可以使用閾值的概念,最多幾分鍾(比如 2 分鍾)比較仍然有效?
第一步是不要將一個東西存儲為它不是的東西。 如果這些是時間,則應將它們存儲為 times 。 字符串用於向用戶表示; 底層存儲是為了現實。
所以現在讓我們將時間存儲為日期組件:
let t1 = DateComponents(hour:17, minute:4)
let t2 = DateComponents(hour:17, minute:5)
現在很容易找出它們相距多遠:
let cal = Calendar(identifier: .gregorian)
if let d1 = cal.date(from: t1),
let d2 = cal.date(from: t2) {
let diff = abs(d1.timeIntervalSince(d2))
// and now decide what to do
}
您首先需要將字符串分離為數組,然后才能進行比較。
/* That two arrays are A1 and A2 */
let minute1 = Int(A1[0])*60+Int(A1[1])
let minute2 = Int(A2[0])*60+Int(A2[1])
這可能對你有幫助。 我認為@Sweeper 不明白這是一個時間,而不是一個日期。
您可以將字符串轉換為分鍾,從另一個中減去一個並檢查絕對值是否小於閾值:
extension String {
var time24hToMinutes: Int? {
guard count == 5, let hours = Int(prefix(2)), let minutes = Int(suffix(2)), Array(self)[2] == ":" else { return nil }
return hours * 60 + minutes
}
func time24hCompare(to other: String, threshold: Int = 2) -> Bool {
guard let lhs = time24hToMinutes, let rhs = other.time24hToMinutes else { return false }
return abs(lhs-rhs) < threshold
}
}
測試:
"17:02".time24hCompare(to: "17:04") // false
"17:03".time24hCompare(to: "17:04") // true
"17:04".time24hCompare(to: "17:04") // true
"17:05".time24hCompare(to: "17:04") // true
"17:06".time24hCompare(to: "17:04") // false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.