I'd like to use let rawDataFromArray = NSData(bytes: myArray, length: ???), but don't know how to get the bytes length for my array. Here are some examples of what could my array be:
let arr1 = [1, 2, 3]
let arr2 = [1.0, 23556789000.0]
let arr3 = ["hello", "ok", "👍"]
func arrayLength(myArray: Array) -> Int {
var bytes = 0
for object in myArray {
// not sure what to do here
}
return bytes
}
I'm not sure if going through every element of the array (and in case of strings going through every character, since emojis could have more bytes representing them) is the proper way to do it.
How to get bytes size for array?
Could anyone tell me the proper way to do it?
Or maybe it's just that it is not good practice to convert Array to NSData in Swift?
I've also seen Converting Swift Array to NSData for persistent storage and Converting array of bytes to NSData and Custom Array to NSData, but couldn't figure out how to get bytes size for such arbitrary array.
Stringstructure (which has a fixed size) contains opaque pointers to the actual character storage.struct Stringhas members which are not part of the "visible" API (but you can see them in the debugger). Some of these are pointers to the actual storage used for the string. (So for example, identical strings can share storage.) – The point is thatstruct Stringis not self-contained. If you pack that into NSData, transfer it somewhere else and unpack it, it will contain invalid pointers. – Of course you can create NSData from an array of strings, but have to append each string (e.g. as NUL-terminated UTF-8 string) separately.