0

I want to modify the values of a CNPostalAddress, which I obtained from the postalAddress property of a CLPlacemark.

Since CNPostalAddress has immutable properties, I want to convert it to a CNMutablePostalAddress. However, there doesn't seem to be a clean way to do that. My current method is this:

extension CNPostalAddress {
    var mutableAddress: CNMutablePostalAddress {
        let address = CNMutablePostalAddress()

        address.city = city
        address.country = country
        address.postalCode = postalCode
        address.state = state
        address.street = street

        [...]

        return address
    }
}

Is there a better way to do this conversion?

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
  • I don't think so. CNMutablePostalAddress has no initializers and you can't cast from CNPostalAddress to CNMutablePostalAddress – Leo Dabus Oct 19 '18 at 23:03
  • @LeoDabus Yes, that's what I found as well. Seems strange, since `NSMutableAttributedString`, another non-Swifty class actually has an initializer with an `NSMutableString` parameter. – Tamás Sengel Oct 19 '18 at 23:06
  • +1, not sure why this was down voted. I do a lot with CNContact, didn't know the CNPostalAddress is used elsewhere, so this was good-for-me. – benc Nov 10 '18 at 05:41

1 Answers1

5

CNPostalAddress is a class that extends NSObject. This means you have access to mutableCopy.

let contact = ... // some CNPostalAddress instance obtained elsewhere
let newContact = contact.mutableCopy() as! CNMutablePostalAddress
newContact.city = "Here"

No need to copy individual properties.

Or as an update to your extension:

extension CNPostalAddress {
    var mutableAddress: CNMutablePostalAddress {
        return mutableCopy() as! CNMutablePostalAddress
    }
}

let contact = ... // some CNPostalAddress instance obtained elsewhere
let newContact = contact.mutableAddress
newContact.city = "Here"
rmaddy
  • 314,917
  • 42
  • 532
  • 579