UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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) }
    }
}

1      

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!

4      

thanks ! I got this

1      

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?

1      

TimelineSchedule is a protocol.

PeriodicTimelineSchedule is a struct that conforms to the TimelineSchedule protocol.

1      

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

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.