SLN SLN - 1 year ago 57
Swift Question

Problems to invoke the default method in protocal extention

By creating a method in protocol extension only, the default method can then be defined. I.e. if the method is not implemented in the type (Structure, Class and Enum), then calling the method is actually invokes the method in the protocol extension.

are two protocols, By using the type constraint on the protocol extension of
,I shall able to use the property
inside the implementation of my extension.

protocol TeamRecord {
var wins: Int { get }
var losses: Int { get }

protocol PlayoffEligible {
var minimumWinsForPlayoff: Int{ get }

extension TeamRecord where Self: PlayoffEligible {
func isPlayoffEligible() -> Bool {
return self.wins > minimumWinsForPlayoff

struct TeamInGroupA: TeamRecord{
var wins: Int
var losses: Int
var minimunWinsForPlayoff: Int

let BasketBallLA = TeamInGroupA(wins: 19, losses: 20, minimunWinsForPlayoff: 10)

Problem: I cannot find the function
inside the object created by the type of which conforms to

enter image description here

Question: How can I call the method in the protocol extension which employed a type constraint that makes the method using a property from anther protocol

Thanks a lot for your time and help

Answer Source

You cannot find a PlayoffEligible extension method inside your struct TeamInGroupA, because TeamInGroupA does not adopt PlayoffEligible:

struct TeamInGroupA: TeamRecord {

Think of protocols as imposing a sort of type hierarchy. If a struct adopts a protocol, it "is" that type. So, TeamInGroupA will have PlayoffEligible extension methods only if a TeamInGroupA "is" a PlayoffEligible. But in your code, it is not.

If you want TeamInGroupA to adopt PlayoffEligible, you need to say so, explicitly:

struct TeamInGroupA: TeamRecord, PlayoffEligible {