ios - Swift 展开的值仍然显示为可选

标签 ios swift option-type forced-unwrapping

我正在努力让名称值在没有 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/

相关文章:

objective-c - 有什么方法可以禁用 'message to nil not throwing an error' 行为(即我想要错误)?

ios - TableViewController 中 SearchBar 中的取消按钮需要双击

ios - 在 iOS 上使用 AudioQueue 录制小端 PCM

swift - SpriteKit 粒子文件位置

c++ - 如何 boost::serialize std/boost::optional?

ios - Objective-c 如何以编程方式导入文件?

ios - IB Designables 在使用自定义类时发出奇怪的警告

swift - 连接 IBOutlet 时 IBAction 停止工作

c++ - 在模板函数中使用 boost::optional arguments 作为参数

ios - 无法将类型 '[String : AnyObject]?.Type'(又名“Optional<Dictionary<String, AnyObject>>.Type)的值转换为预期的参数类型