Home > front end >  SwiftUI why does conforming to ShapeStyle allow this
SwiftUI why does conforming to ShapeStyle allow this

Time:07-23

extension Color {
    static var vinceBackground: Color { Color( red: 0.74, green: 0.01, blue: 0.98) }
}

extension ShapeStyle where Self == Color {
    static var vinceBackground: Color { Color( red: 0.74, green: 0.01, blue: 0.98) }
}

struct ContentView: View {
    var body: some View {
        Circle()
            .frame(width: 300, height: 200)
            .background(Color.vinceBackground)

    }
}

So I have a question, if I don't extend ShapeStyle here I will have to refer to color as Color.vincebackGround but if I extend ShapeStyle where the adopting protocol is Color then this works, why is that? This background modifier init accepts something that conforms to the ShapeStyle protocol, so how come adding this extension lets me omit the Color. I mean .vinceBackground is still referring to Color.vinceBackground right? So how come adding this extension to ShapeStyle lets it infer that?

And also why even would I extend ShapeStyle instead of Color could anyone give me a good example? Is it just to shorten it so I can write .vinceBackground instead of Color.vinceBackground?

CodePudding user response:

If you look at the background modifier definition, you'll notice that it only accepts ShapeStyle and Shape related views. That is why you must confirm ShapeStyle

    /// - Parameters:
    ///   - style: An instance of a type that conforms to ``ShapeStyle`` that
    ///     SwiftUI draws behind the modified view.
    ///   - edges: The set of edges for which to ignore safe area insets
    ///     when adding the background. The default value is ``Edge/Set/all``.
    ///     Specify an empty set to respect safe area insets on all edges.
    ///
    /// - Returns: A view with the specified style drawn behind it.
    @inlinable public func background<S>(_ style: S, ignoresSafeAreaEdges edges: Edge.Set = .all) -> some View where S : ShapeStyle

CodePudding user response:

Because a Color is a ShapeStyle but not all ShapeStyles are a Color.

ShapeStyle would have to know about every object that conforms to it and check all of them for static variables.

In the extension Color you are only adding it to the Color and in extension ShapeStyle you are housing the variable in ShapeStyle

  • Related