1

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()
2
  • 2
    You set number to 1, then you increment it to 2. What behavior were you expecting from this? Commented Jul 13, 2017 at 20:30
  • @ConnorG every time I initiate the class the number should increase for example File1 , File2 , File3 Commented Jul 13, 2017 at 20:31

1 Answer 1

4

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
        ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.