带有 \(var) 的字符串导致 "unwrapping an optional value" 错误

String with `\(var)` causes "unwrapping an optional value" error

我有一个这样的循环,它创建了一个代表 url:

的字符串
    for(var i = 1; i < 6; i++)
    {
        let urlString: String = "http://{...}/data/\(i).txt"
        var downloader = FileDownloader(url: urlString, array: peopleArray, table: theTable)

        downloaderQueue.addOperation(downloader)
    }

FileDownloader构造函数如下:

let urlString: String
var personArray: Array<Person> = []
var person: Person
let table: UITableView

init(url: String, array: Array<Person>, table: UITableView)
{
    self.urlString = url
    self.person = Person()
    self.personArray = array
    self.table = table
}

当这段代码运行时,lldb 给我错误:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) 

我知道问题是字符串,因为调试器输出:

downloader  Lecture_14.FileDownloader   0x000000016fd89f60  0x000000016fd89f60
    Foundation.NSOperation  NSOperation     
    urlString   String  "unexpectedly found nil while unwrapping an Optional value" 
        _core   _StringCore

知道为什么会这样吗?

在 Xcode 中,按住 option 键并单击每个正在使用的变量:urlString、peopleArray 和 theTable。

出现的弹出窗口将通过附加 ? class 名字。

从上面的代码来看,urlString 不应该是可选的,因此不应该是问题所在。但是检查其他正在使用的变量,看看它们是否是可选的。

如果是这样,使用这样的东西:

if let checkedPeopleArray = peopleArray {
   // now you can use checkedPeopleArray and be sure it is not nil
}

其他几点可以使您的代码更 Swift-like:

你的循环可以这样写,使用 Swift 的范围而不是传统的 C 风格循环:

for i in 1..<6 {
    let urlString: String = "http://{...}/data/\(i).txt"
}

在声明数组时,Apple 从 Swift 的第一个版本中更改了这一点。而不是:

var personArray: Array<Person> = []

尝试:

var personArray: [Person]()  // empty array for Person objects

在你的初始化中:

init(url: String, array: [Person], table: UITableView)

功能相同,但我觉得最好使用出现的语言更改,因为没有人知道 when/ifApple 可能会删除旧语法。