Your co-worker needs to get passed the learning curve of these “unsafe” APIs
and note that Swift arrays are complex data structures. &allZeros does not give
you a pointer to a bunch of zero bytes, but a pointer to a struct that contains
the private implementation details of allZeros array.
Here is the correct way to do it:
func allZerosUUID() -> String {
let allZeros = [UInt8](repeating: 0, count: 32)
return allZeros.withUnsafeBufferPointer { NSUUID(uuidBytes:
$0.baseAddress).uuidString }
}
> On Mar 1, 2017, at 2:35 PM, Russell Finn via swift-users
> <[email protected]> wrote:
>
> 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
>
> _______________________________________________
> swift-users mailing list
> [email protected]
> https://lists.swift.org/mailman/listinfo/swift-users
_______________________________________________
swift-users mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-users