If you want to sort the addresses in a particular order, you can do something like:
let addresses = contact.postalAddresses.sorted { (address1, address2) -> Bool in
return self.labelOrder(address1.label) < self.labelOrder(address2.label)
}
Where
let labelPreferredOrder = [CNLabelHome, CNLabelWork, CNLabelPhoneNumberMobile, CNLabelPhoneNumberiPhone]
private func labelOrder(_ label: String?) -> Int {
if let label = label, let index = labelPreferredOrder.index(of: label) {
return index
}
return labelPreferredOrder.count + 1
}
You might want to add some hard coded label prefixes, too, in case user used their own hard-coded values, or if the contacts may have been imported from third-party source that didn't employ the localized, standard contacts prefixes:
let labelPreferredOrder = [CNLabelHome, "Home", "home", CNLabelWork, "Work", "work", CNLabelPhoneNumberMobile, "Mobile", "mobile", "Cell", "cell", CNLabelPhoneNumberiPhone]
Bottom line, sort these any way you want. Note, you don't need the phone-related labels for addresses, but you might include them in case you want to sort phone numbers using a similar technique.
To get the lines of the street address in an array (where you can fetch line 1 and line 2 separately, split it by \n:
let streetLines = address.value.street.split(separator: "\n")
Then a two line street address would be rendered as an array of strings
["123 Main Street", "Suite 100"]