Cannot assign to value: 'saveName' is a 'let' constant error in swift 4

this is my errors and I can't put var before them

Cannot assign to value: 'saveName' is a 'let' constant

Cannot assign to value: 'savePath' is a 'let' constant

this is my codes

internal static func download(fileURL:String, savePath:String?, saveName:String?, onDownloadComplete:((_ url:String, _ filePath:String) -> Void)?){
        if saveName == nil {
            saveName = getFileName(url: fileURL)
        }
        if savePath == nil {
            savePath = AppDelegate.downloadPath + "/" + saveName!
        }

One way to write this would be to assign the passed in parameter to a new variable. This would also get rid of the implicitly unwrapped saveName, use constants (let), and make the code more concise.

internal static func download(fileURL: String, savePath: String?, saveName: String?, onDownloadComplete:((_ url: String, _ filePath: String) -> Void)?){
    let name = saveName ?? getFileName(url: fileURL)
    let path = savePath ?? AppDelegate.downloadPath + "/" + name

The reason for your error message is that the parameters that are passed into a function are always constants (unless they are passed inout, but that has different semantics entirely).

2 Likes

And if you don't want to make up new names, you can create a local variable with the same name:

let saveName = saveName ?? getFileName(url: fileURL)

This does mean you won't be able to access the parameter from then on, as the local variable shadows it.

3 Likes