简体   繁体   English

如何在swift中比较阈值内的两个字符串值?

[英]How to compare two string values within a threshold value in swift?

I am trying to write a code where I have got two time[hh:min] data(String type).我正在尝试编写一个代码,其中我有两次 [hh:min] 数据(字符串类型)。 Need to just compare but the challenge is my code undergones some validations before returning the final values.只需要进行比较,但挑战是我的代码在返回最终值之前经过了一些验证。 so the assertion fails sometimes stating expected value is [17:04] but actual is [17:05].所以断言有时会失败,说明预期值为 [17:04],但实际值为 [17:05]。 Is there any way where we can use concept of Threshold that upto few minutes (say 2 mins) the comparison will still be valid?有什么方法可以使用阈值的概念,最多几分钟(比如 2 分钟)比较仍然有效?

Step one is do not store a thing as something that it is not.第一步是不要将一个东西存储为它不是的东西。 If these are times, they should be stored as times .如果这些是时间,则应将它们存储为 times Strings are for representation to the users;字符串用于向用户表示; underlying storage is for reality.底层存储是为了现实。

So now let's store our times as date components:所以现在让我们将时间存储为日期组件:

let t1 = DateComponents(hour:17, minute:4)
let t2 = DateComponents(hour:17, minute:5)

Now it's easy to find out how far apart they are:现在很容易找出它们相距多远:

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
}

You first need to seprate your string to an array, and then you can compare.您首先需要将字符串分离为数组,然后才能进行比较。

/* 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])

This may help you.这可能对你有帮助。 I think that @Sweeper did not understand that it is a time, not a date.我认为@Sweeper 不明白这是一个时间,而不是一个日期。

You can convert your string to minutes, subtract one from another and check if the absolute value is less than the threshold:您可以将字符串转换为分钟,从另一个中减去一个并检查绝对值是否小于阈值:

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
    }
}

Testing:测试:

"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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM