iOS.Lover
iOS.Lover

Reputation: 6051

Swift :Issue with increment Int inside String

I am trying to increment Int value inside String , but I don't why the increment only happens one time ! here is the code :

class DownloadFile : NSObject {

  var number = 1
init(url : String) {

    urlOfDownload = url
    fileUrl = URL(string: url)!


    //Added by me , checks if file is already exist try to add new file name
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String
    let url = NSURL(fileURLWithPath: path)
    let filePath = url.appendingPathComponent(fileUrl.lastPathComponent)!.path
    let fileManager = FileManager.default
    if fileManager.fileExists(atPath: filePath) {


            number += 1

        print("FILE AVAILABLE")
        nameOfDownload = "\(fileUrl.deletingPathExtension().lastPathComponent)\(number).\(fileUrl.pathExtension)"

    } else {

        print("FILE NOT AVAILABLE")
        nameOfDownload = fileUrl.lastPathComponent
    }

}

}

Using class :

let downloadFile = DownloadFile(url: url)
    downloadFile.startDownload()

Upvotes: 1

Views: 419

Answers (1)

vacawama
vacawama

Reputation: 154583

You need to make your var static to share it between class instances:

class DownloadFile : NSObject {

    static var number = 1
    init(url : String) {
        ...
        DownloadFile.number += 1
        ...
    }
}

Upvotes: 4

Related Questions