Neo Teo Neo Teo - 1 year ago 120
Swift Question

how to save array to ios document directory?

I have my own type of array and how can i save this array to ios document directory. Here is my code

struct Patient {
var lastName: String?
var firstName: String?
var offpatients = [Patient]()
let patient = Patient(lastName: lastName as String?, firstName: firstName as String?)

for p in offpatients {
print("offline patients \(p)")

Answer Source

We can't save struct object to NSArray directly and we even can't make use of any array of struct to save in Document Directory. So we need some conversions.

First of all decide the path to store in Document Directory. In this function we will pass the name of the array file to be stored in Document Directory

func getFilePath(fileName:String) -> String {
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    let filePath = url.appendingPathComponent(fileName)?.path
    return filePath!

Main Process starts from here. Now we will pass the Patient array of struct in this function which will convert in NSMutableArray and save in DocumentDirectory.

func convertAndSaveInDDPath (array:[Patient]) {
    let objCArray = NSMutableArray()
    for obj in array {

        // we have to do something like this as we can't store struct objects directly in NSMutableArray
        let dict = NSDictionary(objects: [obj.firstName ?? "",obj.lastName ?? ""], forKeys: ["firstName" as NSCopying,"lastName" as NSCopying])

    // this line will save the array in document directory path.
    objCArray.write(toFile: getFilePath(fileName: "patientsArray"), atomically: true)

So, call this method for the saving process.

convertAndSaveInDDPath(array: offpatients)

In order to see the physical file, just print the result of getFilePath(fileName: "patientsArray"). It will print something like this according to your system settings.


Navigate to your generated path and you will find patientArray file saved in the Document Directory location.

Now in order to fetch it back in the same form (swift array of struct)

func getArray() -> [Patient]? {
    var patientsArray = [Patient]()
    if let _ = FileManager.default.contents(atPath: getFilePath(fileName: "patientsArray")) {
        let array = NSArray(contentsOfFile: getFilePath(fileName: "patientsArray"))
        for (_,patientObj) in array!.enumerated() {
            let patientDict = patientObj as! NSDictionary
            let patient = Patient(lastName: patientDict.value(forKey: "lastName") as? String, firstName: patientDict.value(forKey: "firstName") as? String)

        return patientsArray
    return nil

Just call this function and you will get your saved array back in the same swift array of struct form.

let patientRetrievedArray = getArray()

And you are done.

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download