'withUnsafeBytes' is deprecated'

Hey guys,

I'm getting the following Warning on my function:

'withUnsafeBytes' is deprecated: use withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R instead

But can't really figure out what is going on:

func hexString(data: Data) -> String {
            return data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> String in
                let buffer = UnsafeBufferPointer(start: bytes, count: data.count)
                return buffer.map{String(format: "%02hhx", $0)}.reduce("", {$0 + $1})
            }
    }

There are two overloads (versions) of Data's withUnsafeBytes.

  1. The old declaration gives you an UnsafePointer<UInt8> inside the closure, which is a security issue because it doesn't limit the pointer to the actual length of the data bytes.

  2. The new declaration gives you UnsafeRawBufferPointer inside the closure, which limits pointer access to the actual length of the data, so it's safer to use. It's also more compact:

    func hexString(data: Data) -> String {
        return data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> String in
            return bytes.map{String(format: "%02hhx", $0)}.reduce("", {$0 + $1})
        }
    }
'withUnsafeBytes' is deprecated'
 
 
Q