swift – 如何将UInt64转换为Int64?

前端之家收集整理的这篇文章主要介绍了swift – 如何将UInt64转换为Int64?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
试图在Swift中调用dispatch_time正在努力,这就是为什么:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,10 * NSEC_PER_SEC),dispatch_get_main_queue(),{
            doSomething()
            })

导致错误:“无法找到接受提供的参数的’*’的重载”.

NSEC_PER_SEC是一个UInt64,因此可以进行一些实验:

let x:UInt64 = 1000
let m:Int64 = 10 * x

导致与上述相同的错误

let x:UInt64 = 1000
let m:Int64 = 10 * (Int64) x

结果“一行上的连续陈述必须以’;’分隔”

let x:UInt64 = 1000
let m:Int64 = 10 * ((Int64) x)

结果“预期”,“分隔符”

let x:UInt64 = 1000
let m:Int64 = (Int64)10 * (Int64) x

结果“一行上的连续陈述必须以’;’分隔”

等等

该死的Swift编译器,我放弃了.如何将UInt64转换为Int64,和/或如何在swift中使用dispatch_time?

将UInt64转换为Int64是不安全的,因为UInt64的数字可能大于Int64.max,这将导致溢出.

这是一个用于将UInt64转换为Int64的片段,反之亦然:

// Extension for 64-bit integer signed <-> unsigned conversion

extension Int64 {
    var unsigned: UInt64 {
        let valuePointer = UnsafeMutablePointer<Int64>.allocate(capacity: 1)
        defer {
            valuePointer.deallocate(capacity: 1)
        }

        valuePointer.pointee = self

        return valuePointer.withMemoryRebound(to: UInt64.self,capacity: 1) { $0.pointee }
    }
}

extension UInt64 {
    var signed: Int64 {
        let valuePointer = UnsafeMutablePointer<UInt64>.allocate(capacity: 1)
        defer {
            valuePointer.deallocate(capacity: 1)
        }

        valuePointer.pointee = self

        return valuePointer.withMemoryRebound(to: Int64.self,capacity: 1) { $0.pointee }
    }
}

这简单地将UInt64的二进制数据解释为Int64,即大于Int64.max的数字将是负的,因为64位整数的最高位的符号位.

如果你只想要正整数,那就得到绝对值.

编辑:根据行为,您可以获得绝对值,或:

if currentValue < 0 {
    return Int64.max + currentValue + 1
} else {
    return currentValue
}

后一种选择类似于剥离符号位.例如:

// Using an 8-bit integer for simplicity

// currentValue
0b1111_1111 // If this is interpreted as Int8,this is -1.

// Strip sign bit
0b0111_1111 // As Int8,this is 127. To get this we can add Int8.max

// Int8.max + currentValue + 1
127 + (-1) + 1 = 127
原文链接:https://www.f2er.com/swift/319939.html

猜你在找的Swift相关文章