# withUnsafeBytes' is deprecated

**URL:** <https://forums.swift.org/t/withunsafebytes-is-deprecated/24848>\
**Category:** Using Swift\
**Created:** [May 25, 2019, 8:49am UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848 "2019-05-25T08:49:09Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![gerriet](https://avatars.discourse-cdn.com/v4/letter/g/dc4da7/32.png) [@gerriet](https://forums.swift.org/u/gerriet)\
**Post date:** [May 25, 2019, 8:49am UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848/1 "2019-05-25T08:49:09Z")

</div>

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

But I cannot figure out, how to use this correctly.

Any Help?

Current code:  
let bigNum: UInt64 = data.withUnsafeBytes  
{ (pointer: UnsafePointer) -\> UInt64 in  
return pointer.pointee  
}  
Works, but creates warning.

Gerriet.

---

<div class="post-metadata">

**Author:** ![kansaichris](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kansaichris/32/2703_2.png) [@kansaichris](https://forums.swift.org/u/kansaichris)\
**Post date:** [May 25, 2019, 10:11am UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848/2 "2019-05-25T10:11:40Z")

</div>

It looks like [you're not the only one who's run into issues with `UnsafeRawBufferPointer`](https://mjtsai.com/blog/2019/03/27/swift-5-released/) (h/t @mjtsai). I'm not terribly familiar with the API so I don't know how safe the following code is, but at least it compiles:

```swift
let bigNum: UInt64 = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> UInt64 in
    return bytes.load(as: UInt64.self)
}

```

You could write this more concisely as follows:

```swift
let bigNum: UInt64 = data.withUnsafeBytes { bytes in
    return bytes.load(as: UInt64.self)
}

```

Or you could even make it a one-liner:

```
let bigNum = data.withUnsafeBytes { $0.load(as: UInt64.self) }

```

---

<div class="post-metadata">

**Author:** ![Gerriet\_M\_Denkmann1](https://avatars.discourse-cdn.com/v4/letter/g/58f4c7/32.png) [@Gerriet\_M\_Denkmann1](https://forums.swift.org/u/Gerriet_M_Denkmann1)\
**Post date:** [May 25, 2019, 11:12am UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848/3 "2019-05-25T11:12:38Z")

</div>

Thanks a lot! Works perfectly.

Gerriet.

---

<div class="post-metadata">

**Author:** ![Andrew\_Trick](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/andrew_trick/32/323_2.png) [@Andrew\_Trick](https://forums.swift.org/u/Andrew_Trick)\
**Post date:** [May 25, 2019, 11:12pm UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848/4 "2019-05-25T23:12:25Z")

</div>

> `let bigNum = data.withUnsafeBytes { $0.load(as: UInt64.self) }`

That's safe if data is 8-byte aligned. And it's currently the best way to do it IMO. In the past I've suggested adding Data APIs to bypass the unsafe closure-based API, like this, but we're not there yet:

e.g. `let bigNum = data.load(as: UInt64.self) }`

We also don't have an API for loading unaligned data, so if alignment can't be guaranteed you still have to do something like this:

```swift
  var bigNum = Int64(0)
  withUnsafeMutableBytes(of: &bigNum) {
    data.copyBytes(to: $0, from: 0..<MemoryLayout<Int64>.size)
  }

```

...and it just took me a long time to figure out the right incantation for that.

---

<div class="post-metadata">

**Author:** ![Gerriet\_M\_Denkmann1](https://avatars.discourse-cdn.com/v4/letter/g/58f4c7/32.png) [@Gerriet\_M\_Denkmann1](https://forums.swift.org/u/Gerriet_M_Denkmann1)\
**Post date:** [May 26, 2019, 3:50am UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848/5 "2019-05-26T03:50:55Z")

</div>

Thanks for clearing this up!

One additional question: would  
let subdata = data.subdata(in: 3 ..\< 3 + 8)  
be 8-byte aligned?

But I find this all very confusing.

I really would like to write:  
let bigNum = UInt64(data: data)  
or:  
let bigNum = UInt64(data: data, offset: 7)

and would expect nil (if data is too short) or a value.

Even better (as I am receiving data in network byte order) would be:  
let bigNum = UInt64(data: data, endianness: .bigEndian) // converts from bigEndian to host endianness

I am sure the compiler could figure this out.

Gerriet.

---

<div class="post-metadata">

**Author:** ![Martin](https://avatars.discourse-cdn.com/v4/letter/m/73ab20/32.png) [@Martin](https://forums.swift.org/u/Martin)\
**Post date:** [May 26, 2019, 3:26pm UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848/6 "2019-05-26T15:26:01Z")

</div>

> [@Andrew\_Trick](#):
>
> ```
> var bigNum = Int64(0)
> withUnsafeMutableBytes(of: &bigNum) {
> data.copyBytes(to: $0, from: 0..<MemoryLayout<Int64>.size)
> }
> 
> ```

Unless I am mistaken, this can be shortened to

```
var bigNum = Int64(0)
withUnsafeMutableBytes(of: &bigNum) {
  data.copyBytes(to: $0)
}

```

since `copyBytes()` limits the number of bytes to copy to the size of the target buffer.

---

<div class="post-metadata">

**Author:** ![Andrew\_Trick](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/andrew_trick/32/323_2.png) [@Andrew\_Trick](https://forums.swift.org/u/Andrew_Trick)\
**Post date:** [May 26, 2019, 6:44pm UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848/7 "2019-05-26T18:44:00Z")

</div>

> ```swift
> var bigNum = Int64(0)
> withUnsafeMutableBytes(of: &bigNum) {
> data.copyBytes(to: $0)
> }
> 
> ```

Thanks @Martin. I just realized that API was added to DataProtocol where I forgot to look. Now I can close this bug! [[SR-9720] Foundation Data API: add Data.copyBytes methods taking UnsafeRawBufferPointer. · Issue #3553 · apple/swift-corelibs-foundation · GitHub](https://bugs.swift.org/browse/SR-9720)

---

<div class="post-metadata">

**Author:** ![Andrew\_Trick](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/andrew_trick/32/323_2.png) [@Andrew\_Trick](https://forums.swift.org/u/Andrew_Trick)\
**Post date:** [May 26, 2019, 8:02pm UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848/8 "2019-05-26T20:02:28Z")

</div>

I filed a new JIRA for this, [[SR-10778] Foundation Data should have an API for reading/writing arbitrary trivial types (without exposing unsafe pointers) · Issue #3329 · apple/swift-corelibs-foundation · GitHub](https://bugs.swift.org/browse/SR-10778), based on an old radar rdar://problem/28201395 Add Foundation Data API for moving typed values into and out of raw bytes. /cc @Philippe_Hausler, @itaiferber I would be nice to have this soon so people aren't always forced to understand how to work with unsafe pointers.

> [@Gerriet\_M\_Denkmann1](#):
>
> One additional question: would  
> let subdata = data.subdata(in: 3 ..\< 3 + 8)  
> be 8-byte aligned?

No, unless `data` happened to be misaligned to begin with.

> I really would like to write:  
> let bigNum = UInt64(data: data)  
> or:  
> let bigNum = UInt64(data: data, offset: 7)
> 
> and would expect nil (if data is too short) or a value.

I suppose extensions could be provided for the scalar types. I don't think it can replace a generic `copyBytes` API. Note that Data APIs use indices instead of byte offsets. I also think it's more conventional for Swift libraries to trap on something the user would normally check for themselves rather than force the user to unwrap an optional.

> Even better (as I am receiving data in network byte order) would be:  
> let bigNum = UInt64(data: data, endianness: .bigEndian) // converts from bigEndian to host endianness

~~I think the conventional way to do it is  
 `UInt64(data: data).bigEndian`~~

Actually, I agree with your original suggestion. I added a note about this to the JIRA bug.

---

<div class="post-metadata">

**Author:** ![Florentin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/florentin/32/8437_2.png) [@Florentin](https://forums.swift.org/u/Florentin)\
**Post date:** [December 3, 2019, 11:32am UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848/9 "2019-12-03T11:32:56Z")

</div>

I have the same warning in my function and really don't know how to fix it. Anyone have any idea ?

> ```
> func writeData(_ data: Data) {
>     
> _ = data.withUnsafeBytes { // warning here
> self.write($0, maxLength: data.count)
> }
> }
> 
> ```

---

<div class="post-metadata">

**Author:** ![eskimo](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/eskimo/32/13558_2.png) [@eskimo](https://forums.swift.org/u/eskimo)\
**Post date:** [December 3, 2019, 10:14pm UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848/10 "2019-12-03T22:14:20Z")

</div>

The use of `write(_:maxLength:)` makes me suspect you have an extension on `OutputStream`. If so, see [this DevForums thread](https://forums.developer.apple.com/thread/126311).

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

---

<div class="post-metadata">

**Author:** ![Florentin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/florentin/32/8437_2.png) [@Florentin](https://forums.swift.org/u/Florentin)\
**Post date:** [December 11, 2019, 1:08pm UTC](https://forums.swift.org/t/withunsafebytes-is-deprecated/24848/11 "2019-12-11T13:08:39Z")

</div>

This change fixed my warning:

```
func writeData(_ data: Data) {
        
        _ = data.withUnsafeBytes {
            write($0.bindMemory(to: UInt8.self).baseAddress!, maxLength: data.count)
        }
    }

```
