[swift-users] Using withUnsafePointer on char arrays within C structs

Russell Finn rsfinn at gmail.com
Wed Mar 1 16:35:10 CST 2017


Thanks to Joe and Quinn for their answers. I have a related followup — a
co-worker learning Swift wrote the following function:

    func allZerosUUID() -> String {
        var allZeros = [UInt8](repeating: 0, count: 32)
        return withUnsafePointer(to: &allZeros) { zerosPtr in
            return NSUUID(uuidBytes: zerosPtr).uuidString
        }
    }

but was puzzled that Xcode 8.2.1 gave an error "Cannot convert value of
type 'UnsafePointer<_>' to expected argument type 'UnsafePointer<UInt8>!'"
on the line with the NSUUID initializer.  Their expectation was that
`zerosPtr` would be of type `UnsafePointer<UInt8>` because `allZeros` is of
type `[UInt8]`.

They discovered that they could work around this by adding a call to
`withMemoryRebound`:

    func allZerosUUID() -> String {
        var allZeros = [UInt8](repeating: 0, count: 32)
        return withUnsafePointer(to: &allZeros) { zerosPtr in
            zerosPtr.withMemoryRebound(to: UInt8.self, capacity:
allZeros.count) { zerosPtr in
                return NSUUID(uuidBytes: zerosPtr).uuidString
            }
        }
    }

but felt that this should be unnecessary. Perhaps I'm missing something
simple, but I was unable to explain this compiler behavior; can anyone on
the list do so?

(Yes, I did point out that they could pass `&allZeros` directly to
`NSUUID(uuidBytes:)`.)

Thanks — Russell
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170301/130fdc24/attachment.html>


More information about the swift-users mailing list