Ok, so this is my question: what mental trick do people use to remember to use Data's instance method withUnsafeBytes when they need to get at the raw pointer to the data's contents, instead of doing what I inevitably always do, which is use the global withUnsafeBytes on my Data, which instead gives me a pointer to the Data itself, not the contents...

I can never, ever, seem to remember this trap long term, and for whatever reason it usually takes me a half hour of debugging my bad access, verifying byte counts all over the place, before I ultimately realize that I've done it again, I used the global method on Data instead of Data's instance method!

Is it just me?

what mental trick do people use …

I don’t have a mental trick for this specifically but I do have some general suggestions for avoiding the problem:

  • Do you really need withUnsafeBytes(…)? — I see a lot of folks use this API in situations where there are better, and more importantly safer, solutions. I’ve posted about this extensively both here and on DevForums.

  • Custom wrappers — If you find yourself repeatedly using withUnsafeBytes(…) for some common task, factor that code out into a wrapper that you use in preference. For example, I have an extension on InputStream and OutputStream that adds methods that work in terms of Data.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple


Thanks Quinn,

Yeah unfortunately I do really need withUnsafeBytes, maybe part of the problem is that the need arises too infrequently for me to commit this trap to memory :sweat_smile:

You’re right, I should just write some wrapper to avoid this altogether.

Terms of Service

Privacy Policy

Cookie Policy