答案 0 :(得分:9)
您可以使用正则表达式来实现
let string = "00123456"
let trimmedString = string.replacingOccurrences(of: "^0+", with: "", options: .regularExpression)
好处是没有双重转换,也没有强制展开。
答案 1 :(得分:8)
只需将字符串转换为int,然后再将其转换回字符串即可。它将删除前导零。
let numberString = "00123456"
let numberAsInt = Int(numberString)
let backToString = "\(numberAsInt!)"
结果:" 123456"
答案 2 :(得分:0)
首先,创建Validator然后在任何类中使用它。 这是一个例子,它的工作原理:) 这很快4.0。
class PhoneNumberExcludeZeroValidator {
func validate(_ value: String) -> String {
var subscriberNumber = value
let prefixCase = "0"
if subscriberNumber.hasPrefix(prefixCase) {
subscriberNumber.remove(at: subscriberNumber.startIndex)
}
return subscriberNumber
}
}
用法示例:
if let countryCallingCode = countryCallingCodeTextField.text, var subscriberNumber = phoneNumberTextField.text {
subscriberNumber = PhoneNumberExcludeZeroValidator().validate(subscriberNumber)
let phoneNumber = "\(countryCallingCode)\(subscriberNumber)"
registerUserWith(phoneNumber: phoneNumber)
}
答案 3 :(得分:0)
let number = "\(String(describing: Int(text)!))"