<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Stas Marynych on Medium]]></title>
        <description><![CDATA[Stories by Stas Marynych on Medium]]></description>
        <link>https://medium.com/@masyny12062000?source=rss-ac0732a9d8c7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HZ6OnZTce4Zu8fdKthfFaA@2x.jpeg</url>
            <title>Stories by Stas Marynych on Medium</title>
            <link>https://medium.com/@masyny12062000?source=rss-ac0732a9d8c7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 03:09:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@masyny12062000/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to use generic protocol as a type in Swift? Type erasure]]></title>
            <link>https://medium.com/@masyny12062000/how-to-use-generic-protocol-as-a-type-in-swift-type-erasure-7599faca9f1e?source=rss-ac0732a9d8c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7599faca9f1e</guid>
            <category><![CDATA[type-erasure]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[generics]]></category>
            <dc:creator><![CDATA[Stas Marynych]]></dc:creator>
            <pubDate>Fri, 31 Jul 2020 12:36:56 GMT</pubDate>
            <atom:updated>2020-12-02T23:51:36.070Z</atom:updated>
            <content:encoded><![CDATA[<p>I can bet that each of you at least once faced such type of an error:</p><blockquote>“protocol ‘SomeGenericProtocol’ can only be used as a generic constraint because it has Self or associated type requirements”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbJAk_n6R0jgJPDfgTnAjA.png" /></figure><p>In this article I will try to explain how to get round this type of restriction using <strong>type erasure</strong> approach.</p><p>Firstly, lets imagine in what cases it could be pretty useful. For example, some time ago I wanted to implement a reusable validation mechanism. That is obvious, that each screen will have different number and type of validation subjects (<em>email, password, phone number or address etc.</em>). So the main idea was to create a protocol with associated type which will be used to point to different validation subjects type as an enum to avoid implementing similar protocols for each ViewController that requires some data validation. Therefore, lets create a protocol with<strong> associatedtype (please, take into account that our type should confirm Hashable protocol. We will find out why a bit later) </strong>and some method that will change the state of our fields in case of invalid input.</p><pre>protocol ValidationDelegate: class {<br>    associatedtype ValidationSubject: Hashable<br>    func setState(_ subjects: [ValidationSubject: ValidationResult])<br>}</pre><p>As we created this protocol we should confirm it. I did it like that:</p><pre>extension LoginViewController: ValidationDelegate {<br>    enum Subjects {<br>        case email<br>        case password<br>    }<br>    <br>    typealias ValidationSubject = Subjects<br>    <br>    func setState(_ subjects: [Subjects : ValidationResult]) {<br>        subjects.forEach { error in<br>            switch error.key {<br>            case .email:<br>                // error state of textField<br>            case .password:<br>                // error state of textField<br>            }<br>        }<br>    }<br>}</pre><p>Okey, so now it would be perfect to call this method via delegate / closure etc. But if we declare the property of type <strong>ValidationDelegate </strong>the compile error occurs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7gaT-fsHEjddZATGu4McQ.png" /></figure><p>For this reason, in my opinion type erasure is what we need. There are several ways to do this, but the easiest to my mind is with closures.</p><pre>class ValidationDelegateWrapper&lt;ValidationSubject: Hashable&gt;: ValidationDelegate {<br>    private let _setState: ([ValidationSubject: ValidationResult]) -&gt; Void<br>    init&lt;Base: ValidationDelegate&gt;(_ base: Base) where ValidationSubject == Base.ValidationSubject {<br>        _setState = base.setState<br>    }<br>    func setState(_ subjects: [ValidationSubject: ValidationResult]) {<br>        _setState(subjects)<br>    }<br>}</pre><p>As we can see, there are two generics which we compare with each other (hence associated type should confirms <strong>Hashable</strong> protocol) and notice that <strong>ValidationDelegateWrapper</strong> confirms <strong>ValidationDelegate </strong>protocol<strong> </strong>then pass the method implementation into closure and call it inside of <strong>setState(_ subjects:)</strong> function.</p><p>After that, we can declare our delegate like that:</p><p>private let validationDelegate: ValidationDelegateWrapper&lt;LoginViewController.ValidationSubject&gt;</p><p>And then in my case use initializer:</p><p>LoginPresenter(validationDelegate: ValidationDelegateWrapper(LoginViewController()))</p><p>As you may have noticed, due to that we can use our delegate without any problems:</p><pre>func setEmailsState(result: ValidationResult) {<br>        validationDelegate.setState([.email: result])<br>    }<br>    <br>    func setPasswordsState(result: ValidationResult) {<br>        validationDelegate.setState([.password: result])<br>    }<br>}</pre><p>To sum up, thanks to <strong>ValidationDelegateWrapper </strong>we will be able to reuse our protocol with different subjects type or implementation of <strong>setState(_ subjects:) </strong>method. Also you can download my example from GitHub <a href="https://github.com/StasMarynych/type-erasure">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7599faca9f1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>