Search code examples
swiftinitialization

How to avoid unnecessary initialization in helper function returning an object?


I have a helper function called fileByIndex. This function takes an index parameter, and then uses this parameter to find an existing object, and returns this existing object. In this process, the code initializes an object with var file = File() line, then assigns an existing object to this reference. Here the initialization is actually unnecessary. I wonder if there is any way to avoid this unnecessary initialization & deinitialization.

I thought of (1) Creating a dummy File object for this purpose in global context (2) Giving this dummy object to this helper function as an inout parameter and returning it, but I feel this is not a good approach too.

Is there a proper way to avoid this?

class File {

}

let newFile1 = File()
let newFile2 = File()
let oldFile1 = File()
let oldFile2 = File()

var newFiles = [newFile1, newFile2]
var oldFiles = [oldFile1, oldFile2]


func fileByIndex(index: Int) -> File {

    var file = File()

    if index > 0 {
        file = newFiles[index]
    } else {
        file = oldFiles[index]
    }

    return file

}

Solution

  • You can just declare the variable and not give it value:

    func fileByIndex(index: Int) -> File {
    
        var file: File
    
        if index > 0 {
            file = newFiles[index]
        } else {
            file = oldFiles[index]
        }
    
        return file
    
    }
    

    In fact, file could be declared as a let in this case:

    let file: File