replacementOccurrences(of:"",with:"")Not Working

时间:2018-03-17 07:14:04

标签: swift string

我有一个文本字段,用户输入他们的电话号码。当他们点击“继续”时按钮,文本字段中的文本被分配给名为phoneNumber的全局变量。然后我继续清理任何非整数值的字符串,例如' - ',')'和' +'。当我尝试删除空格时,它并不总是有效。我意识到当我自动填充我的电话号码时它才起作用。自动填充电话号码中的空格是否与键盘中的空格不同?

有人可以帮助我弄清楚这里发生了什么,或者是否有更好的方法来做到这一点?

class LoginViewController: UIViewController {

@IBOutlet weak var phoneNumberTextField: UITextField!
var phoneNumber = ""

@IBAction func continueButton(_ sender: Any) {

    self.phoneNumber = phoneNumberTextField.text!

    for _ in 0...phoneNumber.count {
    self.phoneNumber = self.phoneNumber.replacingOccurrences(of: " ", with: "")
    self.phoneNumber = self.phoneNumber.replacingOccurrences(of: "-", with: "")
    self.phoneNumber = self.phoneNumber.replacingOccurrences(of: "(", with: "")
    self.phoneNumber = self.phoneNumber.replacingOccurrences(of: ")", with: "")
    }

    checkCount(phoneNumber: self.phoneNumber)
}

func checkCount(phoneNumber : String) {
        if phoneNumber.count == 11 {
            self.phoneNumber = "+" + phoneNumber
        }
        else if phoneNumber.count == 10 {
            self.phoneNumber = "+1" + phoneNumber
        }
}
}

1 个答案:

答案 0 :(得分:1)

使用CharacterSet代替replacingOccurrences从字符串中过滤电话号码的最佳方法。

您可以尝试使用以下代码

let components =
    phoneNumber.components(separatedBy: CharacterSet.decimalDigits.inverted)
let phone = components.joined()
print(phone)