Segue Optional Value nil

时间:2016-10-04 09:07:09

标签: ios swift segue swift3

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let newuser = users[indexPath.row]
    let usernname = newuser.name! as String
    print(usernname)
    print(keys[indexPath.row])
    let destinationViewController = ChatViewController()
    destinationViewController.toUid = keys[indexPath.row]
    destinationViewController.topBar.title = usernname
    performSegue(withIdentifier: "toChatView", sender: self)
}

keys [indexPath.row]工作正常但用户名有错误。它说

fatal error: unexpectedly found nil while unwrapping an Optional value

但是当我打印我的username变量时,它打印好了

1 个答案:

答案 0 :(得分:0)

您需要检查用户名是否为零

let usernname = newuser.name! as String

let destinationViewController = ChatViewController()
destinationViewController.toUid = keys[indexPath.row]

if username != nil { // check if this is nil or not
 print(usernname)
 print(keys[indexPath.row])
 destinationViewController.topBar.title = usernname
 performSegue(withIdentifier: "toChatView", sender: self)
}