Declare an array of Int in Realm Swift Declare an array of Int in Realm Swift arrays arrays

Declare an array of Int in Realm Swift


Lists of primitives are not supported yet unfortunately. There is issue #1120 to track adding support for that. You'll find there some ideas how you can workaround that currently.

The easiest workaround is create a object to hold int values. Then the model to have a List of the object.

class Foo: Object {    let integerList = List<IntObject>() // Workaround}class IntObject: Object {    dynamic var value = 0}


Fortunately arrays of primitive types are now supported in Realm 3.0 and above. (Oct 31 2017)

You can now store primitive types or their nullable counterparts (more specifically: booleans, integer and floating-point number types, strings, dates, and data) directly within RLMArrays or Lists. If you want to define a list of such primitive values you no longer need to define cumbersome single-field wrapper objects. Instead, you can just store the primitive values themselves!

class MyObject : Object {    @objc dynamic var myString: String = ""    let myIntArray = List<Int>()}

Source: https://realm.io/blog/realm-cocoa-reaches-3-0/


The accepted offer is very costly in term of memory.You might get a List of very big "n" of objects.

It's not a matter of right and wrong but I think it's good to write here a different workaround.

Another approach:
I decided to use a single string to represent an Int array.

In my Realm class I defined a variable:

dynamic var arrInt: String? = nil

And use it very easily:

let arrToSave = [0, 1, 33, 12232, 394]<MY_CUSTOM_REALM_CLASS>.arrInt = arrToSave.map { String(describing: $0) }.joined(separator: ",")

And the way back:

let strFetched = <MY_CUSTOM_REALM_CLASS>.arrInt let intArray = strFetched.components(separatedBy: ",").flatMap { Int($0) }

Will be happy to hear your feedback, as I think this approach is better.