tonytran tonytran - 6 months ago 61
Swift Question

protocol extension, does not conform to protocol

I am creating a framework named

MyFramework
containing
LoginProtocol.swift
which has some default behaviours

import UIKit

public protocol LoginProtocol {
func appBannerImage() -> UIImage?
func appLogoImage() -> UIImage?
}


extension LoginProtocol {
func appBannerImage() -> UIImage? {
return (UIImage(named: "login_new_top"))
}

func appLogoImage() -> UIImage? {
return (UIImage(named: "appLogo"))

}
}


Next, I am adding a new target to create a demo application named
MyDemoApp
which is using
MyFramework
:

import UIKit
import MyFramework

class LoginViewContainer: UIViewController, LoginProtocol {
// I think I am fine with defaults method. But actually getting an error
}


Currently, I am getting an error from the compiler such as

type 'LoginViewContainer does not conform protocol 'LoginProtocol'


I am not sure why I am getting this message because with protocol extension,the class does not need to conform the protocols

It would be great if I can get some advices about this issue.Thanks

PS:this is a link for these codes. feel free to look at it.

Answer

The problem is that your extension isn't public – therefore it's not visible outside the module it's defined in, in this case MyFramework.

This means that your view controller only knows about the LoginProtocol definition (as this is public), but not the default implementation. Therefore the compiler complains about the protocol methods not being implemented.

The solution therefore is to simply make the extension public:

public extension LoginProtocol {
    func appBannerImage() -> UIImage? {
        return (UIImage(named: "login_new_top")) 
    }

    func appLogoImage() -> UIImage? {
        return (UIImage(named: "appLogo"))

    }
}