Error: instance method 'METHOD' requires that 'CLASS' conform to 'PROTOCOL'

Hi,
Im seeing the below error when I try to compile my code. I couldn't figure out the underlying issue here. Can someone please help me understand what's going on and how to fix this.

error: instance method 'snapshot(state:card:size:)' requires that 'UICollectionViewCell' conform to 'CardViewProtocol'

Code that produces the above error.

// UI Model
struct WelcomeCardUIModel { }

// Protocols
protocol CardViewProtocol {
    associatedtype State
    
    func render(state: State)
}

protocol CardDimensionCalculable {
    associatedtype CardModel

    static func cardDimension(for traitCollection: UITraitCollection, bounds: CGRect, model: CardModel?) -> CGSize
}

// Protocols Usage
class WelcomeCard: UICollectionViewCell { }

extension WelcomeCard: CardViewProtocol {
    func render(state: WelcomeCardUIModel) { }
}

extension WelcomeCard: CardDimensionCalculable {
    static func cardDimension(for traitCollection: UITraitCollection, bounds: CGRect = .zero, model: WelcomeCardUIModel? = nil) -> CGSize {
        return CGSize.zero
    }
}

// Error class
class CardSnapshotTests {
    func testWelcomeCardWithModel() {
        /**
         error: instance method 'snapshot(state:card:size:)' requires that 'UICollectionViewCell'
         conform to 'CardViewProtocol' snapshot(state: WelcomeCardUIModel(), card: WelcomeCard.self)
         */
        snapshot(state: WelcomeCardUIModel(), card: WelcomeCard.self) {
            return WelcomeCard.cardDimension(for: $0, width: UIScreen.main.bounds.width)
        }
    }
    
    private func snapshot<Card: UICollectionViewCell & CardViewProtocol>(state: Card.State, card: Card.Type, size: (UITraitCollection) -> CGSize) {
        /* Code */
    }
}

In the call snapshot(state: WelcomeCardUIModel(), card: WelcomeCard.self) you are not passing an instance of the WelcomeCard type, you are passing the type itself (which is what WelcomeCard.self means). You need to pass an actual object, like you do by invoking WelcomeCardUIModel().

Actually i found the reason, it is a silly mistake made by me.

The below line,

snapshot(state: WelcomeCardUIModel(), card: WelcomeCard.self) {
    return WelcomeCard.cardDimension(for: $0, width: UIScreen.main.bounds.width)
}

supposed to be,

snapshot(state: WelcomeCardUIModel(), card: WelcomeCard.self) {
    return WelcomeCard.cardDimension(for: $0, bounds: UIScreen.main.bounds)
}

Xcode didn't throw error on the exact line where the error was.

Terms of Service

Privacy Policy

Cookie Policy