0

I get the number from a matrix contacts ,which each one have a number of the persone, however my problem is that I want the number in raw in order to I can match with another matrix.

       for a in contacts 

{
        let content: String = a.phone

        let result1 = content.stringByReplacingOccurrencesOfString("(", withString:"")
        let result2 = result1.stringByReplacingOccurrencesOfString(")", withString:"")
        let result3 = result2.stringByReplacingOccurrencesOfString("-", withString:"")
        let result4 = result3.replace(" ", replacement: "")




        println(result4)


       // newNames.append(result4)
      //contador=contador+1
    }
   //result[555 555,999 3188,999 1]

so is not eliminate the spaces why?, why if the other conditions worked well, I also use the:

let result4 = result3.stringByReplacingOccurrencesOfString(" ", withString: "") 

and it does not work why?

//result[555 555,999 3188,999 1]

2 Answers2

1

You are using a different API, replace().

Use the working API, stringByReplacingOccurrencesOfString() instead.

Chaining

Note that you can chain in Swift, which is much more elegant.

let cleanNumber = content
  .stringByReplacingOccurrencesOfString("(", withString:"")
  .stringByReplacingOccurrencesOfString(")", withString:"")
  .stringByReplacingOccurrencesOfString("-", withString:"")
  .stringByReplacingOccurrencesOfString(" ", withString:"")

Filter and map

Also, be aware of the even more concise filter and map APIs.

let content = "(459) 333-4938"
let cleanNumber = content.characters.filter {
    ![" ", "-", "(", ")"].contains($0)
}.map { String($0) }.joinWithSeparator("")
// "4593334938"

NSCharacterSet

And the old NSCharacterSet trick:

let illegal = NSCharacterSet(charactersInString: "1234567890").invertedSet
let cleanNumber = content
   .componentsSeparatedByCharactersInSet(illegal)
   .joinWithSeparator("")
// "4593334938"
Mundi
  • 79,884
  • 17
  • 117
  • 140
-1

You could try extending String to include a function for removing a list of characters.

For Swift 1.2 (not 2):

extension String {
    func removeCharacters(chars: [Character]) -> String {
        return String(filter(self) {find(chars, $0) == nil})
    }
}

let chars: [Character] = ["(", ")", "-", " "]

let result = content.removeCharacters(chars)
Matt Le Fleur
  • 2,708
  • 29
  • 40
  • May I ask, why the downvotes? – Matt Le Fleur Sep 15 '15 at 17:10
  • Try it in Swift 2, there is an error: Cannot invoke 'filter' with an argument list of type '(String, (Character) -> Bool)' – zaph Sep 15 '15 at 17:20
  • Ah thanks for pointing that out, I haven't really been using 2.0 yet, I'll add that to the answer. – Matt Le Fleur Sep 15 '15 at 17:27
  • 1
    Swift 2.0 is imminent, Xcode GM is available. I am already seeing my Swift 1.x answers being down-voted because they are incorrect for 2.0. It s going to be a real pain to find all my Swift answers and adding 2.0 answers. – zaph Sep 15 '15 at 17:34