我正在尝试使用 PropertWrapper 进行电子邮件验证。但是当我尝试用空字符串初始化 eamilId 变量时,我收到错误:调用中的参数标签不正确(有 'wrappedValue:',预期的 'emailId:')
这是我的视图控制器的代码
class ViewController: UIViewController {
var name: String = ""
@EmailWrapper var emailId: String = ""
override func viewDidLoad() {
super.viewDidLoad()
name = "User Name"
emailId = "user123@gmail.com"
updateUserDetails()
}
func updateUserDetails() {
if name.isEmpty || emailId.isEmpty {
print("Please enter valid Name and emailId")
}
else {
print("User data updated successfully")
}
}
}
我的属性包装器的代码是
@propertyWrapper
struct EmailWrapper {
private var value = ""
var wrappedValue: String {
set {
value = newValue
}
get {
return isValidEmail(value) ? value : ""
}
}
init(emailId: String) {
self.value = emailId
}
private func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
}
如何在使用 EmailWrapper 时在 ViewController 中使用默认值(String() )初始化emailId