BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SOLVED: Is there a way to solve this simple bit of code?

Forums > SwiftUI

I wrote this code below without thinking, then quickly realised ofcourse it won't work because the parentasis will interfere with the code. I know I would wrap the whole H and V Stack but it's a lot of code and I prefer not to do it twice. Is there any way to solve this?

 if widthSizeClass == .regular {
                        HStack {
    } else if widthSizeClass == .compact {
                        VStack {
    } else {
                        VStack {
}

Many thanks

   

Perhaps take a look at ViewThatFits to control your layout, or use a switch, or use a function to return the VStack/HStack content, so you're not coding any embedded parentheses. Or code the content as a separate component. Lots of potential solutions, it all depends on how complex your view is going to become.

Steve

   

Maybe use a switch instead of an if statement. I'm assuming your enum has only the 2 .regular and .compact?

enum Sizes {
case regular
case compact
}

let widthSizeClass: Sizes = .compact

switch widthSizeClass {
  case .regular:
    HStack {
      // Your code here
    }
  case .compact:
    VStack {
      // Your code here
    }
}

   

Yes only two but I don't want to include the closing bracket because it's a lot of code and I prefer not to do it twice. Using a switch means I still need to do it twice

   

oh. then just place that repeatable view in another struct / view and call it inside the HStack and VStack.

switch widthSizeClass {
  case .regular:
    HStack {
       YourView()
    }
  case .compact:
    VStack {
        YourView()
    }
}

then you would just have to edit YourView().

struct YourView: some View {
  // your code here
}

@ygeras link is more advanced and you can move to that once you're more versed.

1      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.