-2

Hello I'm currently working on a contacts application and I can't proper show the contact number into the cell, all I want is to display as a String without the Optional text and the (""). Here is my code:

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
}

How Could I display the number under the name?

pacification
  • 5,838
  • 4
  • 29
  • 51
traiantomescu
  • 65
  • 3
  • 12

1 Answers1

1

use this ?? nil-coalescing operator :

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

Take this example:

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

If the operand on the left of ?? is nil then the one on its right is returned. the operand on the left of ?? is NOT nil, then it is unwrapped and returned.

let s2: String? = nil
let s3 = s ?? "World" //In this case s2 is nil, so "World" is returned
type(of: newString)   //String.Type
ielyamani
  • 17,807
  • 10
  • 55
  • 90