We all know that [UInt8] type is not equal UnsafePointer<UInt8>,
But why can I pass [UInt8] type to UnsafePointer<UInt8> type parameter:
let p = UnsafeMutablePointer<UInt8>.allocate(capacity: 4)
p.initialize(repeating: 0, count: 4)
let ary:[UInt8] = [1,2,3,4]
p.assign(from: ary, count: 4) // It's OK, why?
As shown above,p.assign method frist parameter type is UnsafePointer<T>, but It's OK when I pass the type [UInt8]...
Why is that? Thanks! ;)
It's just a shortcut.
An unsafe pointer is effectively a C array: what we are pointing at is the first address of a contiguous block of memory. Therefore Swift gives you some nice help for when you have a Swift array from which you want to write to the memory: this Swift array is nothing whatever like a C array, but nevertheless, you can pass a pointer to the Swift array or even the Swift array itself, including an array literal, and Swift will just do the right thing.