WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Question about extension

Forums > SwiftUI

Hi ! Can anyone explain for me the mean of phase: "where Self == PeriodicTimelineSchedule". I mean, idk what is SELF , can the == operator?.

extension TimelineSchedule where Self == PeriodicTimelineSchedule {
    static var everyFiveSeconds: PeriodicTimelineSchedule {
        get { .init(from: .now, by: 5.0) }
    }
}

   

So there is a protocol called TimelineSchedule. Different data structures can conform to TimelineSchedule. So you could have a PeriodicTimelineSchedule or ExplicitTimelineSchedule or a EveryMinuteTimelineSchedule.

Self refers to the type of whatever it is you are extending.

This extension is saying "extend the TimelineSchedule protocol with a new static computed var property called everyFiveSeconds but only do it when the actual type is a PeriodicTimelineSchedule". In other words, it will not extend any other conforming type (like ExplicitTimelineSchedule or EveryMinuteTimelineSchedule).

extension TimelineSchedule where Self == PeriodicTimelineSchedule {
    static var everyFiveSeconds: PeriodicTimelineSchedule {
        get { .init(from: .now, by: 5.0) }
    }
}

let sched1: PeriodicTimelineSchedule = .everyFiveSeconds       //allowed
let sched2: EveryMinuteTimelineSchedule = .everyFiveSeconds    //error!
let sched3: ExplicitTimelineSchedule = .everyFiveSeconds       //error!

3      

thanks ! I got this

   

If TimelineSchedule and PeriodicTimelineSchedule are both protocols, is there a reason that the extension is on TimelineSchedule with a requirement that the instance be a PeriodicTimelineSchedule, rather than make it an extension on PeriodicTimelineSchedule?

   

TimelineSchedule is a protocol.

PeriodicTimelineSchedule is a struct that conforms to the TimelineSchedule protocol.

   

That makes sense. For some reason, I thought that PeriodicTimelineSchedule was a protocol as well. My bad.

   

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.