我正在努力让名称值在没有Optional(...)
. 我以为我正在解开它们,但我无法摆脱可选的。我在 StackOverflow 上找到了一个解决方案,但在那种情况下,涉及到了一个as?
问题,这里不是这种情况。有问题的代码如下。有什么办法可以解开这些吗?我假设我遗漏了一些明显的东西。谢谢。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! ClientCell
cell.setBackground()
let clientKey = clientSectionTitles[(indexPath as NSIndexPath).section]
if let clientValues = clientDict[clientKey] {
if self.sortBy == "First" {
cell.clientName.text = clientValues[(indexPath as NSIndexPath).row].firstName! + " " + clientValues[(indexPath as NSIndexPath).row].lastName!
} else {
cell.clientName.text = clientValues[(indexPath as NSIndexPath).row].lastName! + ", " + clientValues[(indexPath as NSIndexPath).row].firstName!
}
}
return cell
}
*编辑:这是构建字典的代码:
func createClientDict() {
var clientName: String?
clientDict = [String: [Client]]()
clientSectionTitles = [String]()
if self.sortBy == "First" {
apiResults.sort (by: { $0.firstName < $1.firstName })
} else {
apiResults.sort (by: { $0.lastName < $1.lastName })
}
for c in apiResults {
if self.sortBy == "First" {
clientName = "\(c.firstName!) \(c.lastName!)"
} else {
clientName = "\(c.lastName!), \(c.firstName!)"
}
// Get the first letter of the name and build the dictionary
let clientKey = clientName!.substring(to: clientName!.characters.index(clientName!.startIndex, offsetBy: 1))
if var clientValues = clientDict[clientKey] {
clientValues.append(c)
clientDict[clientKey] = clientValues
} else {
clientDict[clientKey] = [c]
}
}
// Get the section titles from the dictionary's keys and sort them in ascending order
clientSectionTitles = [String](clientDict.keys)
clientSectionTitles = clientSectionTitles.sorted { $0 < $1 }
}
*编辑:我还应该提到,这只发生在 Swift 3 中。它在 Swift 2.2 中运行良好。