简体   繁体   中英

Can i compare two bytes values on basis of nearly equal to in swift

i have two values in bytes in two different variables . i want to perform a certain action whenever values are nearly equal to each other. I there any method in swift in which i can perform any action on variables values nearly equal to. If recommend me some code , tutorial or article to achieve this. I am new to swift so please avoid down voting.

let string1 = "Hello World"
let string2 = "Hello"
let byteArrayOfString1: [UInt8] = string1.utf8.map{UInt8($0)} //Converting HELLO WORLD into Byte Type Array
let byteArrayOfString2: [UInt8] = string2.utf8.map{UInt8($0)} //Converting HELLO into Byte Type Array

if byteArrayOfString1 == byteArrayOfString2 {
    print("Match")
}else {
    print("Not Match")

}

For more Help, Visit https://medium.com/@gorjanshukov/working-with-bytes-in-ios-swift-4-de316a389a0c

确切地说,我不这么认为有这样的方法来比较近似值,但如果你讨论你想要做什么,我们可以找到一个更好的替代解决方案。

Here is the Solution:

func nearlyEqual(a: Float, b: Float, epsilon: Float) -> Bool {
let absA = abs(a)
let absB = abs(b)
let diff = abs(a - b)
if a == b {
    return true
} else if (a == 0 || b == 0 || absA + absB < Float.leastNonzeroMagnitude) {
    // a or b is zero or both are extremely close to it
    // relative error is less meaningful here
    return diff < (epsilon * Float.leastNonzeroMagnitude)
} else {
    return diff / (absA + absB) < epsilon
}
}

Then you can use it like :

    print(nearlyEqual(a: 1.2, b: 1.4, epsilon: 0.2))

This will return true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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