Mark Carols Mark Carols - 27 days ago 13
iOS Question

How to get rid of a "non-breaking space" inside a Swift string?

I retrieved some strings from

AddressBook.framework
's
ABRecordCopyValue
method by casting the returned value of
takeRetainedValue()
as a
String
object.

let unmanagedFirstNameProperty = ABRecordCopyValue(person, kABPersonFirstNameProperty)
if unmanagedFirstNameProperty != nil {
contactFirstName = unmanagedFirstNameProperty!.takeRetainedValue() as? String
}

let formattedName:String = contactFirstName.replaceOccurrences(of: " ", with: "")
print(formattedName)


I want to get rid of the spaces inside this
String
object by calling
replaceOccurrences(of:with:)
method, but that doesn't work (the spaces are still there after I call this method) and I was told by the Apple Framework Reference that this is usually because of the string encoding, containing "non-break spaces" which I've heard a lot about, but I have no idea how to make a "non-break space" into a normal space. Is this even possible? If so, what would be the best approach to make the characters inside a
String
compatible with the
replaceOccurrences(of:with:)
method?

Answer

In you code, where you have contactFirstName.replaceOccurrences(of: " ", with: "") is that space character typed in with the option key held down? If you type a space with the option key held down, you should get a non-breaking space.

Then you can replace it with a normal space, or an empty string if you wish.

Comments