kekkeme kekkeme - 8 days ago 5
iOS Question

ios swift class conforming protocol

I am trying to learn swift and want to use protocol oriented programming approach. What i want to achieve is simple but i could not find any way.

lets say i have Outlet which is textfield. I want that textfield conforms protocol like ValidatesName protocol. Is there any way to do it?
I do not want to make new class which subclass UITextField and conforms protocol. I want to use for this specific property.

@IBOutlet weak var nameTextField:UITextField!<Conforms ValidatesName>
@IBOutlet weak var emailTextField:UITextField!<Conforms ValidatesEmail>
@IBOutlet weak var passwordTextField:UITextField!<Conforms ValidatesPassword>


Thanks

Answer

Your issue is that while you can add protocol conformance via an extension, the extension is applied to the class, not an instance of that class. This means that you can say something like:

extension UITextField: ValidatesName {...}

But this will make all instances of UITextField conform to ValidatesName

Similarly, you could also say

extension UITextField: ValidatesEmail{...}

But now all instances of UITextField will conform to ValidatesName and ValidatesEmail.

Having separate Validates... protocols doesn't seem like the right approach anyway. The basic signature of your protocol is something like var isValid: Bool; this doesn't change between name and email. What does change is the validation logic and this has to live somewhere. This, coupled with the fact that you need subclasses in order to work with Interface Builder would suggest that a single protocol Validatable that can be adopted by your various subclasses is a more reasonable approach.

protocol Validatable  {
    var isValid: Bool { get }
}

Now, you can define subclasses of UITextField that conform to this protocol (You can add the conformance via an extension to your subclass if you like, I just wanted to save space here)

class NameTextField: UITextField, Validatable {

    var isValid: Bool {
        get {
            guard let text = self.text else {
                return false
            }

            return !text.isEmpty
        }
    }
}

class EmailTextField: UITextField, Validatable {
    var isValid: Bool {
        get {
            guard let text = self.text else {
                return false
            }

            return text.contains("@")
        }
    }
}

Now, you can add your textfields to an array, and have something like:

@IBOutlet weak var nameTextField:NameTextField!
@IBOutlet weak var emailTextField:EmailTextField!

var validatableFields:[Validatable]!

override func viewDidLoad() {
    super.viewDidLoad()

    self.validatableFields = [nameTextField,emailTextField]
}

...

for field in validateableFields {
    if !field.isValid() {
        print("A field isn't valid")
    }
}
Comments