Home > Blockchain >  how to make return type a LinearGradient or an AngularGradient in swift based on a condition?
how to make return type a LinearGradient or an AngularGradient in swift based on a condition?

Time:09-26

I have a function that currently returns LinearGradient as a background color. I would like to modify the return type such that the return type is either LinearGradient or AngularGradient based on a value of a variable?

This is the code I have:

func colors() -> LinearGradient {
   return LinearGradient(
            gradient: Gradient(colors: [
                Color(red: 135/255, green: 206/255, blue: 235/255),
                Color(red: 255/255, green: 160/255, blue: 122/255)
            ]),
            startPoint: .topLeading,
            endPoint: .top
        )
 }

Instead, I would like to do something like this:

enum BackgroundType {
   case linear
   case angular
}

then do the following: (the function is used inside .background() modifier)

func colors(backgroundColor: BackgroundType) -> ShapeStyle {
   if backgroundColor == .linear {
    return LinearGradient(
            gradient: Gradient(colors: [
                Color(red: 135/255, green: 206/255, blue: 235/255),
                Color(red: 255/255, green: 160/255, blue: 122/255)
            ]),
            startPoint: .topLeading,
            endPoint: .top
        )
   } else {
       return AngularGradient(gradient: Gradient(colors: [
            Color(red: 135/255, green: 206/255, blue: 235/255),
            Color(red: 255/255, green: 160/255, blue: 122/255)
        ]),
                        center: .topLeading,
                        angle: .degrees(180   45))
 }

Any suggestions please? Thanks!

CodePudding user response:

Turn your colors function into a ViewBuilder. Add @ViewBuilder, return some View, and remove the return statements. Then this function will return the appropriate View based upon the backgroundColor:

@ViewBuilder
func colors(backgroundColor: BackgroundType) -> some View {
    if backgroundColor == .linear {
        LinearGradient(
            gradient: Gradient(colors: [
                Color(red: 135/255, green: 206/255, blue: 235/255),
                Color(red: 255/255, green: 160/255, blue: 122/255)
            ]),
            startPoint: .topLeading,
            endPoint: .top
        )
    } else {
        AngularGradient(gradient: Gradient(colors: [
            Color(red: 135/255, green: 206/255, blue: 235/255),
            Color(red: 255/255, green: 160/255, blue: 122/255)
        ]),
                        center: .topLeading,
                        angle: .degrees(180   45))
    }
}
  • Related