【问题标题】:Deleting URL not working swift 3删除 URL 不起作用 swift 3
【发布时间】:2017-02-25 08:29:16
【问题描述】:

我在这里做错了什么? 我正在尝试删除一个给定的文件,而我看到的所有documentationexamples 都让它看起来应该可以工作。

func deleteThisFile(fileToDelete: String) {
    let tempLocalDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    do {
        let directoryContents = try FileManager.default.contentsOfDirectory(at: tempLocalDir!, includingPropertiesForKeys: nil, options: [])
        let tempList = directoryContents.filter{ $0.absoluteString.contains(fileToDelete) }

        //tried these things:
        try FileManager.removeItem(tempList.first) // Argument labels '(_:)' do not match any available overloads
       /*
        * try FileManager.removeItem(at: tempList.first!) // Ambiguous reference to member 'removeItem(atPath:)'
        * 
        * try FileManager.removeItem(atPath: (tempList.first?.absoluteString)!) // Ambiguous reference to member 'removeItem(atPath:)'
        */ 

    } catch let error as NSError {
        print(error.localizedDescription)
    }
}

未注释的是 FileManager.removeItem 在我键入时自动提示的内容。

任何关于错误的澄清都会很棒

【问题讨论】:

    标签: swift swift3


    【解决方案1】:

    在 Swift 3 中,您应该使用 removeItem(at:),它是 NSFileManager 的实例方法。而且你需要在交给NSFileManager之前解开可选的包装。

    if let url = tempList.first {
        try FileManager.default.removeItem(at: url)
    }
    

    【讨论】:

    • 为什么需要'.default'?我的意思是,它似乎有效,我很感激,我只是不明白为什么需要 .default
    • 因为您需要NSFileManagerFileManager 的实例来调用removeItem(at:)。除了使用该单例,您还可以实例化一个新的 FileManager,但您始终需要一个实例来调用该方法。
    猜你喜欢
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多