0

我正在尝试使用 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

4

1 回答 1

1

当您应用属性包装器时:

@EmailWrapper var emailId: String = ""

Swift 编译器实际上会生成对属性包装器初始化程序的初始化程序的调用,如下所示:

EmailWrapper(wrappedValue: "")

但是,EmailWrapper没有这样的初始化程序。它唯一的初始化器有参数标签emailId:

要解决此问题,您只需更改初始化程序的参数标签:

init(wrappedValue: String) {
    self.value = wrappedValue
}
于 2020-06-20T05:38:44.143 回答