Capturing values ​​in nested closures

What is the correct syntax for using a captured value in a nested closure?

I have the following working code to calculate CRC32 from an integer value using a library zlib.

func testCrc()
{
    var x: UInt32 = 0xffffffff

    let result = withUnsafePointer(to: &x, {
        $0.withMemoryRebound(to: Bytef.self, capacity: 4) {
            crc32(0, $0, 4)
        }
    })

    XCTAssertEqual(0xffffffff, result)
}

I want to create a standalone universal function that can calculate CRC32 from any value. For this, in addition to the value itself, I also need to calculate and pass its size, so I can not use the explicit size - 4 - as I used in the above code.

But it's hard for me to find the right syntax to pass the calculated size to the inner closure.

func calculateCrc32<T>(_ crc: UInt, value: inout T) -> UInt
{
    let size = MemoryLayout.size(ofValue: value)
    let result = withUnsafePointer(to: &value, {
        $0.withMemoryRebound(to: Bytef.self, capacity: size) {
            crc32(crc, $0, size) // error
        }
    })
    return result
}

Above code shows a rather confusing compiler error for a parameter $0:

"UnsafeMutablePointer < _ > " 'UnsafePointer!'

, , crc32(crc, $0, size) crc32(crc, $0, 4), 4 .

?

+4
1

. , "" - crc32(), be uInt:

func calculateCrc32<T>(_ crc: UInt, value: inout T) -> UInt
{
    let size = MemoryLayout.size(ofValue: value)
    let result = withUnsafePointer(to: &value, {
        $0.withMemoryRebound(to: Bytef.self, capacity: size) {
            crc32(crc, $0, uInt(size))
        }
    })
    return result
}

crc32(crc, $0, 4), " " 4 , uInt, .

crc32(crc, $0, size), Swift .

numericCast(), , ( ).

inout, :

func calculateCrc32<T>(_ crc: UInt, value: T) -> UInt {
    var value = value
    let size = MemoryLayout.size(ofValue: value)
    let result = withUnsafePointer(to: &value, {
        $0.withMemoryRebound(to: Bytef.self, capacity: size) {
            crc32(crc, $0, numericCast(size))
        }
    })
    return result
}
+4

Source: https://habr.com/ru/post/1657062/


All Articles