I need to find out the size of an array (Swift 4 AnyObject) I just downloaded. Every mobile device has some free memory (size varies per user) and I need a way to examine the size of my download. I have searched and can't find a reasonable answer. Hope you can help!
1 Answers
This seems to be impossible currently. But if you just need a rough estimate, you can use class_getInstanceSize
:
func size<T: AnyObject>(_ array: [T]) -> Int {
return class_getInstanceSize(T.self) * array.count
}
For this example array
class Test {
var a: Bool = false
var b: Int = 0
var c: String = ""
}
let array = [Test(), Test(), Test()]
you will get a size of 168. See this post for more information.
Of course, this approach will not work well with fields of variable length, for example with strings or arrays. The only possibility I see to get an accurate value is to write a function for each possible class to calculate the exact number of bytes need. For a string, for example, you can calculate the number of bytes with
"test".data(using: .utf8)!.count
But even with this approach you will not get the real size of the memory Swift uses internally to store the array.
So the question is: Why do you need to know the size of the array? And what is the reason that you do not know the size of downloaded data? If those data are received from outside, they must already be encoded in a byte representation, so counting should be quite easy.

- 2,930
- 1
- 20
- 25
-
Glad to reply about my intent. I use Firestore with costs me money every time a user reads or writes (I expect thousands of users). This adds up I want to cut cost and every person phone is different – user3783935 Apr 03 '18 at 00:18
-
Glad to reply about my intent. I use Firestore with costs me money every time a user reads or writes (I expect thousands of users). This adds up, I want to cut cost and every's person phone is different, some have more memory than others. If I want to download maybe 10,000 or more items, I need to know how much memory I have to play with. Ideally I want to download once, then just read from internal memory. All this has to be dynamic, I'm working on plan B for limited memory, lots more to say, but that's the gist. – user3783935 Apr 03 '18 at 00:26