在 swift 3 中使用扩展时使用未解析的标识符

Use of unresolved identifier while using extension in swift 3

我制作了一个字符串扩展,用于验证 Swift 3 语言的表单。 代码如下:

import UIKit
extension String {
    // Validating Email ID
    func isValidEmail(testStr:String) -> Bool {
        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: testStr)
    }
    // Validating the User name
    func isValidUserName(testStr:String) -> Bool {
        let RegEx = "\A\w{7,18}\z"
        let Test = NSPredicate(format:"SELF MATCHES %@", RegEx)
        return Test.evaluate(with: testStr)
    }
    // Validating the phone number
    var isPhoneNumber: Bool {
        do {
            let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
            let matches = detector.matches(in: self, options: [], range: NSMakeRange(0, self.characters.count))
            if let res = matches.first {
                return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.characters.count
            } else {
                return false
            }
        } catch {
            return false
        }
    }
    // validating the password 
    /*
    Use the function of Swift 3.0.
         1. 8 characters length
         2. alphabet
         3. special character
         regex Syntax Explanation :
         (?=.[a-z]) for Character.
         (?=.[$@$#!%?&]) for special character.
         {8,} for length which you want to prefer.
     */
    func isPasswordValid(_ password : String) -> Bool{
        let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[a-z])(?=.*[$@$#!%*?&])[A-Za-z\d$@$#!%*?&]{8,}")
        return passwordTest.evaluate(with: password)
    }
    // validating the password and confirm password are same........................
    func isPasswordSame(password: String , confirmPassword : String) -> Bool {
        if password == confirmPassword{
            return true
        } else {
            return false
        }
    }
    // validating Blank Text........................
    var  isBlank:Bool {
        return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty
    }
}

但是当我尝试通过代码在其他视图控制器中使用此扩展 class 时:

   if isValidEmail("kirit@gmail.com"){
            print("Validate EmailID")
        }
        else{
            print("invalide EmailID")
        }

我收到错误:

isValidEmail 不是松散函数。您已将其定义为 String 上的 instance 函数。你需要说

"someString".isValidEmail(testStr:"someOtherString")

这没有任何意义,但您就是这样配置的。如果你那样写,你的代码将编译通过(尽管它会是非常愚蠢的代码)。

只需将您的定义更改为

extension String {
// Validating Email ID
func isValidEmail() -> Bool {
    self.validate...
}

然后在您的代码中将其用作

@someString".isValidEmail()