Search code examples
iosswiftstructios9

iOS: create a struct in swift with credentials


I have to create a struct to check if two UITextField are valid. And my idea is this, is it a good way to create a struct?

struct Credentials{
func isCorrect() -> Bool {
    guard let username = emailTF.text else {
        return false
    }
    guard let password = passwordTF.text else {
        return false
    }

    return true
}

but I have some question:

  • how can I pass the values of emailTextField and passwordTF inside the struct? with an init method?
  • and is it better have some var or let inside the struct or is also a good idea have only a method inside a struct?

thanks


Solution

  • You can creare a struct like this

    struct Credentials {
        let email: String
        let password: String
    
        init?(email:String?, password: String?) {
            guard let email = email, password = password else { return  nil }
            self.email = email
            self.password = password
        }
    
        var correct: Bool {
            // do your check
            guard email.isEmpty == false && password.isEmpty == false else { return false }
            return true
        }
    }
    

    As you can see correct is a computed property, non a function because it does't need any params.

    Usage

    let correct = Credentials(email: emailTF.text, password: passwordTF.text)?.correct == true