ppshein ppshein - 5 months ago 18
Swift Question

Cannot convert value of type 'String' to expected argument type

I've created separate swift class in my project to collect all required information and validation as follow:

Config.swift

public class Config: NSObject {
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
let result = range != nil ? true : false
return result
}
}


But problem is when I call that function in anther class, I've faced following error:

if (Config.isValidEmail(txtEmail.text!))



Cannot convert value of type 'String' to expected argument type
'Config'


If I did like that as follow, got different error.

Config.isValidEmail(txtEmail.text)



Cannot convert value of type 'String?' to expected argument type
'Config'


I don't know why. Please help me how to solve.

Answer

You care calling isValidEmail(_:) as a class method, but it's an instance method.

I think you want to make isValidEmail(_:) a class method.

public class Config: NSObject {
    static func isValidEmail(testStr:String) -> Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
        let result = range != nil ? true : false
        return result
    }
}

Note: the static specifier.

Comments