GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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      

Hacking with Swift is sponsored by try! Swift Tokyo.

SPONSORED Ready to dive into the world of Swift? try! Swift Tokyo is the premier iOS developer conference will be happened in April 9th-11th, where you can learn from industry experts, connect with fellow developers, and explore the latest in Swift and iOS development. Don’t miss out on this opportunity to level up your skills and be part of the Swift community!

Get your ticket here

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.