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

Specialized Extensions

Forums > SwiftUI

Hi! Was doing a lesson of the 100 days of SwiftUI and there was a moment where Paul added an extension to the ShapeStyle protocol instead of the Color one, like this:

extension ShapeStyle where Self == Color { ... }

But even after he kind of explained the reason, i still don't understand why is this a better approach compared to do the extension directly in "Color".

2      

This ShapeStyle protocol is what the background() modifier uses, so what we really want to do is extend Color but do so in a way that all the SwiftUI modifiers using ShapeStyle work too.

So other modififier like .foregroundStyle(_:), .stroke(_:style:) and .tint(_:), however you would not be able to use the extension static var darkBackground in these if you did not use ShapeStyle

2      

@Renato brings up memories from a year ago!

But even after he kind of explained the reason, i still don't understand why is this a better approach

See -> ShapeStyle Discussion

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.