使用this answer,我想给我的ViewDidLoad中的变量分配一个字符串,因为我将使用这个数组填充一个表。

let downloads : String?

// Get the document directory url
let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

do {
    // Get the directory contents urls (including subfolders urls)
    let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
    print(directoryContents)

    // if you want to filter the directory contents you can do like this:
    let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
    //print("mp3 urls:",mp3Files)
    let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent }
    //print("mp3 list:", mp3FileNames)

    let downloads = mp3FileNames

} catch {
    print(error.localizedDescription)
}

首先,如果我打印没有变量的mp3文件名,它就会打印。所以mp3下载解压代码看起来不错。
第二,当我为downloads添加变量时,事情就崩溃了。XCode标记我没有在其他地方使用该变量,即使它在do循环中重新出现:Immutable value 'cars' was never used; consider replacing with '_' or removing it
我对斯威夫特不熟悉。用mp3FileNames中的字符串设置此变量的正确方法是什么?

最佳答案

首先有一条规则:
变量仅在声明它的作用域(作用域是一对大括号)及其子作用域中可见。
局部变量

let downloads = mp3FileNames

do块中声明,因此它与顶层同名的变量不是同一对象。局部声明的变量在更高级别上隐藏同名的变量。
还有另外两个主要问题。
较高级别的变量声明为可选常量。你不能改变它!
较高级别的变量声明为String,而mp3FileNames是字符串数组。
如果这两个downloads都是同一个对象,您将得到关于这些问题的编译器错误。
解决方案:
将更高级别的变量声明为字符串的空数组
var downloads = [String]()

并通过删除mp3FileNames关键字将let分配给此变量
downloads = mp3FileNames

关于ios - 在Swift 3中在do循环之外使用变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48762765/

10-12 05:22
查看更多