2017-07-13 2 views
1

J'essaie d'incrémenter la valeur Int à l'intérieur de String, mais je ne sais pas pourquoi l'incrément ne se produit qu'une seule fois! voici le code:Swift: Problème avec l'incrément Int inside String

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 
    } 

} 

} 

classe en utilisant:

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

Vous définissez le numéro 1, vous augmentez-le à 2. Quel comportement attendiez-vous de cela? – Connor

+0

@ConnorG chaque fois que je lance la classe le nombre devrait augmenter par exemple File1, File2, File3 –

Répondre

4

Vous devez faire votre varstatic pour le partager entre les instances de la classe:

class DownloadFile : NSObject { 

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