在单元格中显示 contact.phoneNumber

Show contact.phoneNumber into cell

你好,我目前正在开发一个联系人应用程序,但我无法在单元格中正确显示联系人号码,我只想显示为不带可选文本和 ("") 的字符串。这是我的代码:

let cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath)
    let contact: CNContact!

    if inSearchMode {
        contact = filteredData[indexPath.row]
    } else {
        contact = contactList[indexPath.row]
    }

    cell.textLabel?.text = "\(contact.givenName) \(contact.familyName) \((contact.phoneNumbers.first?.value as? CNPhoneNumber)?.stringValue) "

    return cell
}

如何显示姓名下方的号码?

使用此 ?? nil-coalescing 运算符:

"\(contact.givenName ?? "") \(contact.familyName ?? "") \((contact.phoneNumbers.first?.value as? CNPhoneNumber)?.stringValue ?? "") "

举个例子:

let s: String? = "Hello"
let newString = s ?? "World" //s is not nil, so it is unwrapped and returned
type(of: newString)          //String.Type

如果??左边的操作数为nil,则返回右边的那个。 ?? 左边的操作数不是 nil,然后它被解包并返回。

let s2: String? = nil
let s3 = s ?? "World" //In this case s2 is nil, so "World" is returned
type(of: newString)   //String.Type