Search code examples
iosswiftrealm

Importing CSV Data to Realm Results in "null" String Instead of Swift nil for Optional String


I am importing data from a CSV file into a local Realm database. One of the properties in my Realm model is a String that's defined as optional (String?).

When I encounter a CSV field with an empty value (i.e., ,,), upon importing it into Realm, it displays as null in Realm Studio. Not a "null" String. However, in Swift, when I retrieve this property, it returns "null" as a String instead of nil. The property is optional in my Swift class.

@objc dynamic var name: String? = nil

Is there a way to handle empty CSV values such that they're imported into Realm as actual nil values in Swift? I want to ensure that the optional String property is correctly represented as nil in my Swift code?


Solution

  • Realm Studio shows nil values as "null" where properties contain nil, as in an optional with no value.

    Here's an example. Create a Test modal with two properties, a non optional and an optional

    class Test: Object {
        @Persisted var name = ""
        @Persisted var myOptional: String?
    }
    

    Then some code to test what was imported

    let results = realm.objects(Test.self)
    
    for r in results {
        print( type(of: r.myOptional) )
        if r.myOptional == nil {
            print("myOptional was nil")
        } else {
            print("myOptional was not nil")
        }
    }
    

    The above code reads in all of the imported values, gets the type object myOptional is and prints it to console and then determines if it was nil or not.

    Here's the flatfile containing two objects to import called Test.csv. Note that the optional property for the Jay object is "some string" and the optional property for Cindy is empty

    name,myOptional
    Jay,some string
    Cindy,
    

    Then import the flat file which looks like this in Realm Studio

    enter image description here

    run the code and here's the console output

    The myOptional property was of type: Optional<String>
        myOptional was not nil
    The myOptional property was of type: Optional<String>
        myOptional was nil
    

    EDIT:

    Question about handling double quotes in the header and data fields. Here's an example

    "name","myOptional"
    Jay,some string
    Cindy,
    "Hello","World"
    "Hello",
    

    and when importing, the result

    enter image description here