我正在努力让名称值在没有 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 中运行良好。
最佳答案
以下内容来自 Swift 编程语言集合类型文档:
You can also use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:
所以 clientValues[(indexPath as NSIndexPath).row]
返回一个可选值
尝试
cell.clientName.text = (clientValues[(indexPath as NSIndexPath).row].firstName!)!
*已编辑 - 实际上使用可选绑定(bind)更好:
if let fname = clientValues[(indexPath as NSIndexPath).row].firstName! {
cell.clientName.text = fname }
关于ios - Swift 展开的值仍然显示为可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870621/