如何检查在 UITextField 中输入的字符串是 Swift3 中的数字还是字符串?
How to check if the string entered in a UITextField is a number or string in Swift3?
我有一个 UITextField,我们可以在其中输入电子邮件 ID 或我们的 phone 号码。我的问题是可以检查在 UITextField 中输入的文本是 Swift3 中单击按钮时的 phone 数字还是电子邮件 ID?
目前我正在使用以下代码:
func isNumber(text:String)->Bool
{
if let intVal = text.toInt()
{return true}
else
{return false}
}
但它可以验证,输入是否为整数。是否可以知道输入的是emailID还是phone数字?
// Datatype specifier
enum DataType: Int {
case Other = 0 // This can be string
case Number = 1
case Email = 2
}
// Validate Email
func isEmail(emailString: String) -> Bool {
// Sample regex for email - You can use your own regex for email
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegex)
return emailTest.evaluate(with: emailString)
}
// Check Datatype
func checkDataType(text: String)-> DataType {
if let intVal = text.toInt() {
return DataType.Number
} else if isEmail(emailString: text) {
return DataType.Email
} else {
return DataType.Other
}
}
// print datatype
let dataType = checkDataType(text: "Your Input String")
print("DataType = \(dataType)")
我有一个 UITextField,我们可以在其中输入电子邮件 ID 或我们的 phone 号码。我的问题是可以检查在 UITextField 中输入的文本是 Swift3 中单击按钮时的 phone 数字还是电子邮件 ID? 目前我正在使用以下代码:
func isNumber(text:String)->Bool
{
if let intVal = text.toInt()
{return true}
else
{return false}
}
但它可以验证,输入是否为整数。是否可以知道输入的是emailID还是phone数字?
// Datatype specifier
enum DataType: Int {
case Other = 0 // This can be string
case Number = 1
case Email = 2
}
// Validate Email
func isEmail(emailString: String) -> Bool {
// Sample regex for email - You can use your own regex for email
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegex)
return emailTest.evaluate(with: emailString)
}
// Check Datatype
func checkDataType(text: String)-> DataType {
if let intVal = text.toInt() {
return DataType.Number
} else if isEmail(emailString: text) {
return DataType.Email
} else {
return DataType.Other
}
}
// print datatype
let dataType = checkDataType(text: "Your Input String")
print("DataType = \(dataType)")