Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-2025-04-14· OpenAIHugging Face LMArena Human Preference 140K

This is a SwiftUI view. Visually it looks right, but functionally it doesn't work. If I…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with gpt-4.1-mini-2025-04-14’s answer.
  1. User

    This is a SwiftUI view.

    Visually it looks right, but functionally it doesn't work. If I tap on any time, it seems to open up ArticleDetailView for every article - so 6 or more views open simultaneously. Can you fix that?

    import SwiftUI

    struct LatestListViewTest: View { @StateObject private var vm = LatestViewModel() @State private var selectedArticleSlug: String? // State variable to track selected article for navigation

    var body: some View {
        NavigationStack {
            List {
                VStack {
                    if vm.isLoading {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                    } else {
                        
                        // Display the featured article if available
                        if let featuredArticle = vm.articles.first {
                            Section {
                                FeaturedArticleRow(article: featuredArticle)
                            }
    
                        }
                        
                        // Display the rest of the articles
                        ForEach(vm.articles.dropFirst(), id: \.slug) { article in
                            NavigationLink(destination: ArticleDetailView(slug: article.slug)) {
                                ArticleRow(article: article)
                            }
                        }
                        
                    }
                }
                .task {
                    await vm.load() // Load articles when the view appears
                }
                .navigationDestination(for: String.self) { slug in
                    ArticleDetailView(slug: slug) // Navigate to ArticleDetailView when an article is selected
                }
        }
            .listStyle(PlainListStyle())
        }
    }
    

    }

    struct LatestListViewTest_Previews: PreviewProvider { static var previews: some View { LatestListViewTest() } }

  2. Assistant

    Great question! The issue is that you have a VStack inside your List, and then you use a ForEach inside that VStack. This causes SwiftUI to treat the entire VStack as a single row in the list, and the navigation links inside it all get activated together, leading to the "multiple views open" bug.

    How to fix:

    • Remove the VStack and move your loading logic and sections directly into the List.
    • Use Section and ForEach directly as children of List.

    Here's the corrected code:

    import SwiftUI
    
    struct LatestListViewTest: View {
        @StateObject private var vm = LatestViewModel()
        @State private var selectedArticleSlug: String? // State variable to track selected article for navigation
    
        var body: some View {
            NavigationStack {
                List {
                    if vm.isLoading {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                    } else {
                        // Display the featured article if available
                        if let featuredArticle = vm.articles.first {
                            Section {
                                FeaturedArticleRow(article: featuredArticle)
                            }
                        }
                        
                        // Display the rest of the articles
                        ForEach(vm.articles.dropFirst(), id: \.slug) { article in
                            NavigationLink(destination: ArticleDetailView(slug: article.slug)) {
                                ArticleRow(article: article)
                            }
                        }
                    }
                }
                .listStyle(PlainListStyle())
                .task {
                    await vm.load() // Load articles when the view appears
                }
                .navigationDestination(for: String.self) { slug in
                    ArticleDetailView(slug: slug) // Navigate to ArticleDetailView when an article is selected
                }
            }
        }
    }
    
    struct LatestListViewTest_Previews: PreviewProvider {
        static var previews: some View {
            LatestListViewTest()
        }
    }
    

    Key changes:

    • No VStack inside the List.
    • All rows and sections are direct children of the List.

    Why this works

    SwiftUI's List expects its direct children to be rows or sections. Wrapping them in a VStack or similar container causes the list to treat the entire stack as a single row, which breaks navigation and selection logic.


    Summary:
    Always put your ForEach and Section directly inside the List, not inside a VStack or other container. This will fix your navigation bug!

  3. User

    That nearly works. The ArticleRows all display correctly and link correctly. However, the FeatureArticleRow does not link to an article. Can you fix that?

  4. Assistant

    Great catch! The reason the FeaturedArticleRow does not link is because it's not wrapped in a NavigationLink. In your original code, only the non-featured articles are wrapped in a NavigationLink.

    To fix this, you should wrap the FeaturedArticleRow in a NavigationLink, just like you do for the other articles. Here’s how you can do it:


    import SwiftUI
    
    struct LatestListViewTest: View {
        @StateObject private var vm = LatestViewModel()
        @State private var selectedArticleSlug: String? // State variable to track selected article for navigation
    
        var body: some View {
            NavigationStack {
                List {
                    if vm.isLoading {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                    } else {
                        // Display the featured article if available
                        if let featuredArticle = vm.articles.first {
                            Section {
                                NavigationLink(destination: ArticleDetailView(slug: featuredArticle.slug)) {
                                    FeaturedArticleRow(article: featuredArticle)
                                }
                            }
                        }
                        
                        // Display the rest of the articles
                        ForEach(vm.articles.dropFirst(), id: \.slug) { article in
                            NavigationLink(destination: ArticleDetailView(slug: article.slug)) {
                                ArticleRow(article: article)
                            }
                        }
                    }
                }
                .listStyle(PlainListStyle())
                .task {
                    await vm.load() // Load articles when the view appears
                }
                .navigationDestination(for: String.self) { slug in
                    ArticleDetailView(slug: slug) // Navigate to ArticleDetailView when an article is selected
                }
            }
        }
    }
    
    struct LatestListViewTest_Previews: PreviewProvider {
        static var previews: some View {
            LatestListViewTest()
        }
    }
    

    Summary of the fix:

    • The FeaturedArticleRow is now wrapped in a NavigationLink, so tapping it will navigate to the detail view for the featured article.

    Let me know if you need any more tweaks!

  5. User

    One step forward, one step back. Now the FeatureArticleRow links, but it has introduced an ugly vertical line and chevron to the right of it. Keep the link but make the line and chevron go away.

  6. Assistant

    Great observation! The vertical line and chevron are default behaviors of NavigationLink inside a List or Section. If you want the FeaturedArticleRow to be tappable and navigate, but without the chevron and row styling, you need to:

    • Use a button-style navigation (programmatic navigation) instead of a NavigationLink as a row.
    • Use .listRowSeparator(.hidden) to hide the separator if needed.
    • Use .buttonStyle(PlainButtonStyle()) to remove button styling if you use a Button.

    Here’s a clean way to do it using programmatic navigation with navigationDestination and a Button:

    import SwiftUI
    
    struct LatestListViewTest: View {
        @StateObject private var vm = LatestViewModel()
        @State private var selectedArticleSlug: String? // For programmatic navigation
    
        var body: some View {
            NavigationStack {
                List {
                    if vm.isLoading {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                    } else {
                        // Featured Article Row with custom navigation
                        if let featuredArticle = vm.articles.first {
                            Section {
                                Button {
                                    selectedArticleSlug = featuredArticle.slug
                                } label: {
                                    FeaturedArticleRow(article: featuredArticle)
                                        .contentShape(Rectangle()) // Makes the whole row tappable
                                }
                                .buttonStyle(PlainButtonStyle()) // Removes button styling
                                .listRowSeparator(.hidden) // Optional: hides the separator
                            }
                        }
                        
                        // The rest of the articles
                        ForEach(vm.articles.dropFirst(), id: \.slug) { article in
                            NavigationLink(destination: ArticleDetailView(slug: article.slug)) {
                                ArticleRow(article: article)
                            }
                        }
                    }
                }
                .listStyle(PlainListStyle())
                .task {
                    await vm.load()
                }
                .navigationDestination(item: $selectedArticleSlug) { slug in
                    ArticleDetailView(slug: slug)
                }
            }
        }
    }
    
    struct LatestListViewTest_Previews: PreviewProvider {
        static var previews: some View {
            LatestListViewTest()
        }
    }
    

    Key points:

    • The featured article uses a Button to set selectedArticleSlug.
    • The navigation is handled by .navigationDestination(item:).
    • .buttonStyle(PlainButtonStyle()) removes the button highlight.
    • .listRowSeparator(.hidden) removes the separator if you want a cleaner look.
    • No chevron or vertical line will appear.

    This is the standard SwiftUI way to make a custom row tappable and navigable without the default NavigationLink styling.

  7. User

    Closer. That removed the chevron, but the vertical line is still there. Make that go away.

  8. Assistant

    Great follow-up! The vertical line you’re seeing is the default section separator in a List when you use a Section. If you want the featured article to appear as a single, clean, tappable row without the vertical line (and without the chevron), you have a few options:

    Option 1: Remove the Section wrapper

    If you don’t need the section header/footers, just remove the Section and place the button directly in the List:

    import SwiftUI
    
    struct LatestListViewTest: View {
        @StateObject private var vm = LatestViewModel()
        @State private var selectedArticleSlug: String?
    
        var body: some View {
            NavigationStack {
                List {
                    if vm.isLoading {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                    } else {
                        // Featured Article Row without Section
                        if let featuredArticle = vm.articles.first {
                            Button {
                                selectedArticleSlug = featuredArticle.slug
                            } label: {
                                FeaturedArticleRow(article: featuredArticle)
                                    .contentShape(Rectangle())
                            }
                            .buttonStyle(PlainButtonStyle())
                            .listRowSeparator(.hidden) // Hide separator if you want
                        }
                        
                        // The rest of the articles
                        ForEach(vm.articles.dropFirst(), id: \.slug) { article in
                            NavigationLink(destination: ArticleDetailView(slug: article.slug)) {
                                ArticleRow(article: article)
                            }
                        }
                    }
                }
                .listStyle(PlainListStyle())
                .task {
                    await vm.load()
                }
                .navigationDestination(item: $selectedArticleSlug) { slug in
                    ArticleDetailView(slug: slug)
                }
            }
        }
    }
    

    Option 2: Hide Section Separators (iOS 16+)

    If you must use a Section (for header/footers), you can hide the section separators using the new iOS 16+ API:

    Section {
        Button {
            selectedArticleSlug = featuredArticle.slug
        } label: {
            FeaturedArticleRow(article: featuredArticle)
                .contentShape(Rectangle())
        }
        .buttonStyle(PlainButtonStyle())
        .listRowSeparator(.hidden)
    }
    .listSectionSeparator(.hidden) // <-- Add this modifier to the Section
    

    But the simplest and most robust solution is to remove the Section if you don’t need it.


    Summary

    • Remove the Section around the featured article row.
    • Use a Button with .buttonStyle(PlainButtonStyle()) and .listRowSeparator(.hidden).

    This will give you a clean, tappable featured article row with no chevron and no vertical line.

    Let me know if you want a version with a custom background or further styling!

  9. User

    No, that still doesn't work

  10. Assistant

    Thank you for your patience!
    The vertical line you’re seeing is the section separator that appears to the left of the first row in a Section in a SwiftUI List. Even with .listRowSeparator(.hidden), the section separator remains unless you explicitly hide it on the section itself.

    Here’s how to do it correctly (iOS 16+):


    Solution: Hide the Section Separator

    You must use .listSectionSeparator(.hidden) on the Section, not on the row or button.

    import SwiftUI
    
    struct LatestListViewTest: View {
        @StateObject private var vm = LatestViewModel()
        @State private var selectedArticleSlug: String?
    
        var body: some View {
            NavigationStack {
                List {
                    if vm.isLoading {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                    } else {
                        // Featured Article Row in a Section with section separator hidden
                        if let featuredArticle = vm.articles.first {
                            Section {
                                Button {
                                    selectedArticleSlug = featuredArticle.slug
                                } label: {
                                    FeaturedArticleRow(article: featuredArticle)
                                        .contentShape(Rectangle())
                                }
                                .buttonStyle(PlainButtonStyle())
                                .listRowSeparator(.hidden)
                            }
                            .listSectionSeparator(.hidden) // <-- THIS HIDES THE VERTICAL LINE
                        }
                        
                        // The rest of the articles
                        ForEach(vm.articles.dropFirst(), id: \.slug) { article in
                            NavigationLink(destination: ArticleDetailView(slug: article.slug)) {
                                ArticleRow(article: article)
                            }
                        }
                    }
                }
                .listStyle(PlainListStyle())
                .task {
                    await vm.load()
                }
                .navigationDestination(item: $selectedArticleSlug) { slug in
                    ArticleDetailView(slug: slug)
                }
            }
        }
    }
    

    Key Points

    • .listSectionSeparator(.hidden) must be applied to the Section, not the row.
    • .listRowSeparator(.hidden) hides the horizontal separator, but not the vertical section line.
    • This approach removes both the chevron and the vertical line.

    If you still see the line:

    • Make sure you are running on iOS 16 or later.
    • If you don’t need a section, you can remove the Section entirely, but if you want to keep it, the above is the correct way.

    Let me know if this solves it!

  11. User

    No, that still doesn't work.

    Can you think of something completely different to try?

  12. Assistant

    Absolutely! If you want a tappable featured article row at the top of your list, but you want it to look completely custom (no chevron, no vertical line, no section styling), the best approach is to place the featured article outside the List and use a NavigationLink or programmatic navigation.

    Here’s a robust, modern SwiftUI approach:


    Place the Featured Row Above the List

    import SwiftUI
    
    struct LatestListViewTest: View {
        @StateObject private var vm = LatestViewModel()
        @State private var selectedArticleSlug: String?
    
        var body: some View {
            NavigationStack {
                VStack(spacing: 0) {
                    // Featured Article Row OUTSIDE the List
                    if !vm.isLoading, let featuredArticle = vm.articles.first {
                        Button {
                            selectedArticleSlug = featuredArticle.slug
                        } label: {
                            FeaturedArticleRow(article: featuredArticle)
                                .contentShape(Rectangle())
                        }
                        .buttonStyle(PlainButtonStyle())
                        .background(Color(.systemBackground))
                    }
    
                    // The List of other articles
                    List {
                        if vm.isLoading {
                            ProgressView()
                                .progressViewStyle(CircularProgressViewStyle())
                                .padding()
                        } else {
                            ForEach(vm.articles.dropFirst(), id: \.slug) { article in
                                NavigationLink(destination: ArticleDetailView(slug: article.slug)) {
                                    ArticleRow(article: article)
                                }
                            }
                        }
                    }
                    .listStyle(PlainListStyle())
                }
                .task {
                    await vm.load()
                }
                .navigationDestination(item: $selectedArticleSlug) { slug in
                    ArticleDetailView(slug: slug)
                }
            }
        }
    }
    

    Why this works

    • The featured article is not in the List at all, so it gets no list or section styling, no chevron, no vertical line.
    • The rest of your articles are in the List and behave as normal.
    • Tapping the featured article uses programmatic navigation, so you can style it however you want.

    This is the most flexible and visually clean solution in SwiftUI.
    You can further style the featured row, add padding, or a divider below it if you want.


    Let me know if this finally gives you the look and behavior you want!

  13. User

    That's different and it works, but now the ArticleRows scroll behind the fixed FeatureArticleRow. The first article should scroll away too.

  14. Assistant

    Great catch!
    You want the FeaturedArticleRow to scroll away with the rest of the list, but still have no chevron or vertical line. The best way to achieve this is to make the FeaturedArticleRow the first row in the List, but not use a NavigationLink or Section for it. Instead, use a Button with programmatic navigation, as before.

    Here’s how you do it:


    import SwiftUI
    
    struct LatestListViewTest: View {
        @StateObject private var vm = LatestViewModel()
        @State private var selectedArticleSlug: String?
    
        var body: some View {
            NavigationStack {
                List {
                    if vm.isLoading {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                    } else {
                        // Featured Article Row as the first row in the List
                        if let featuredArticle = vm.articles.first {
                            Button {
                                selectedArticleSlug = featuredArticle.slug
                            } label: {
                                FeaturedArticleRow(article: featuredArticle)
                                    .contentShape(Rectangle())
                            }
                            .buttonStyle(PlainButtonStyle())
                            .listRowSeparator(.hidden) // Hide the separator if you want
                        }
    
                        // The rest of the articles
                        ForEach(vm.articles.dropFirst(), id: \.slug) { article in
                            NavigationLink(destination: ArticleDetailView(slug: article.slug)) {
                                ArticleRow(article: article)
                            }
                        }
                    }
                }
                .listStyle(PlainListStyle())
                .task {
                    await vm.load()
                }
                .navigationDestination(item: $selectedArticleSlug) { slug in
                    ArticleDetailView(slug: slug)
                }
            }
        }
    }
    

    Key Points:

    • The FeaturedArticleRow is the first row in the List.
    • It uses a Button with .buttonStyle(PlainButtonStyle()) to remove button styling.
    • No Section is used, so no vertical line appears.
    • The row scrolls away with the rest of the list.
    • The rest of the articles use NavigationLink as before.

    This is the most "native" way to achieve your desired behavior in SwiftUI.

    Let me know if this is the scrolling, clean look you want!

  15. User

    No, now we're back to having a vertical line beside the FeatureArticleRow.

    What if we try something totally different again, and have a carousel of 5 FeatureArticleRows (the first 5 articles). They would still scroll away when the user goes down the list of ArticleRows of the rest of the articles.

  16. Assistant

    Great idea!
    You can absolutely do this in SwiftUI by placing a horizontally scrolling carousel (using ScrollView(.horizontal)) as the first row in your List. This way, the carousel will scroll away with the rest of the list, and you can make each featured article tappable without any chevrons or vertical lines.

    Here’s how you can implement it:


    import SwiftUI
    
    struct LatestListViewTest: View {
        @StateObject private var vm = LatestViewModel()
        @State private var selectedArticleSlug: String?
    
        var body: some View {
            NavigationStack {
                List {
                    if vm.isLoading {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                    } else {
                        // Carousel of first 5 articles as the first row in the List
                        if !vm.articles.isEmpty {
                            // Use a horizontal ScrollView for the carousel
                            ScrollView(.horizontal, showsIndicators: false) {
                                HStack(spacing: 16) {
                                    ForEach(vm.articles.prefix(5), id: \.slug) { article in
                                        Button {
                                            selectedArticleSlug = article.slug
                                        } label: {
                                            FeaturedArticleRow(article: article)
                                                .frame(width: 300) // Adjust width as needed
                                                .contentShape(Rectangle())
                                        }
                                        .buttonStyle(PlainButtonStyle())
                                    }
                                }
                                .padding(.vertical, 8)
                                .padding(.horizontal, 16)
                            }
                            .listRowInsets(EdgeInsets()) // Remove default insets for full-width carousel
                            .listRowSeparator(.hidden)
                        }
    
                        // The rest of the articles
                        ForEach(vm.articles.dropFirst(5), id: \.slug) { article in
                            NavigationLink(destination: ArticleDetailView(slug: article.slug)) {
                                ArticleRow(article: article)
                            }
                        }
                    }
                }
                .listStyle(PlainListStyle())
                .task {
                    await vm.load()
                }
                .navigationDestination(item: $selectedArticleSlug) { slug in
                    ArticleDetailView(slug: slug)
                }
            }
        }
    }
    

    Key Points:

    • The carousel is a ScrollView(.horizontal) inside the first row of the List.
    • Each featured article is a Button (no chevron, no vertical line).
    • The carousel scrolls away with the rest of the list.
    • The rest of the articles are shown as usual.
    • You can adjust the .frame(width:) for each carousel item to fit your design.

    This approach is visually appealing, avoids all the List/Section quirks, and gives you a modern, tappable carousel at the top of your list!

    Let me know if you want to tweak the carousel further!

  17. User

    That kinda works, but there is a huge amount of space to the left and right of each of the carousel items. Also, there was no indicator that there were other articles

  18. Assistant

    Great feedback!
    Let’s address both issues:

    1. Excessive horizontal spacing:
      This is likely due to the default List row insets and possibly the .frame(width: 300) on each item.

      • We can remove the insets and use a tighter HStack spacing.
      • We can also use .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) to make the carousel flush with the screen edges.
    2. No indicator of more articles:

      • You can add a subtle horizontal scroll indicator, or
      • You can show a partial next card by reducing the width of each card and adding horizontal padding to the ScrollView.

    Here’s a refined version:

    import SwiftUI
    
    struct LatestListViewTest: View {
        @StateObject private var vm = LatestViewModel()
        @State private var selectedArticleSlug: String?
    
        var body: some View {
            NavigationStack {
                List {
                    if vm.isLoading {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                    } else {
                        // Carousel of first 5 articles as the first row in the List
                        if !vm.articles.isEmpty {
                            // Use a horizontal ScrollView for the carousel
                            ScrollView(.horizontal, showsIndicators: true) {
                                HStack(spacing: 12) {
                                    ForEach(vm.articles.prefix(5), id: \.slug) { article in
                                        Button {
                                            selectedArticleSlug = article.slug
                                        } label: {
                                            FeaturedArticleRow(article: article)
                                                .frame(width: 260) // Slightly less than full width
                                                .contentShape(Rectangle())
                                                .shadow(radius: 2)
                                        }
                                        .buttonStyle(PlainButtonStyle())
                                    }
                                }
                                .padding(.vertical, 8)
                                .padding(.leading, 16)
                                .padding(.trailing, 8) // Less right padding to show next card
                            }
                            .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
                            .listRowSeparator(.hidden)
                        }
    
                        // The rest of the articles
                        ForEach(vm.articles.dropFirst(5), id: \.slug) { article in
                            NavigationLink(destination: ArticleDetailView(slug: article.slug)) {
                                ArticleRow(article: article)
                            }
                        }
                    }
                }
                .listStyle(PlainListStyle())
                .task {
                    await vm.load()
                }
                .navigationDestination(item: $selectedArticleSlug) { slug in
                    ArticleDetailView(slug: slug)
                }
            }
        }
    }
    

    What’s improved:

    • Tighter spacing between carousel items.
    • Reduced card width (.frame(width: 260)) so the next card peeks in, hinting at more content.
    • Horizontal scroll indicator is enabled (showsIndicators: true).
    • Padding is adjusted so the carousel aligns nicely with the list and the next card is visible.

    Tip:
    You can further tweak .frame(width:) and the .padding(.leading)/.padding(.trailing) values to get the exact look you want for your carousel.


    Let me know if this gives you the effect you’re after!

  19. User

    The very first time my app loads, it just sits on a blank screen for 5-10 seconds. What can I do to 1) speed that up and 2) make it feel better for the user, even if I can't speed it up much?

  20. Assistant

    This is a great question and a common challenge in mobile app development!
    Let’s break it down:


    1. Speeding Up the Initial Load

    A. Profile and Optimize Your Data Fetch

    • Profile your network call: Is it slow because of the server, network, or parsing? Use tools like Charles Proxy, Xcode Instruments, or print timestamps.
    • Optimize your API: If you control the backend, return only the data you need for the initial screen.
    • Use background threads: Make sure your data loading is asynchronous and not blocking the main thread.

    B. Cache Data

    • Cache the last successful response (e.g., in UserDefaults, a file, or a database like Realm/CoreData).
    • On app launch, show cached data immediately while fetching fresh data in the background.
    • Update the UI when new data arrives.

    C. Preload Data

    • If your app has a login or splash screen, start loading data as early as possible (even before the main view appears).

    2. Making the Wait Feel Better

    A. Show a Progress Indicator

    • You’re already showing a ProgressView, which is good.
    • Consider using a skeleton view (gray boxes or shimmer effect) to indicate loading content, which feels faster than a spinner.

    B. Show Placeholder Content

    • Show a list of placeholder rows (with shimmer or gray boxes) that look like your real content.
    • This gives users a sense of what’s coming and makes the wait feel shorter.

    C. Add Branding or Animation

    • Show your app logo, a fun animation, or a welcome message during the initial load.
    • This can make the wait feel intentional and less frustrating.

    D. Communicate

    • If loading takes longer than a few seconds, show a message like “Fetching latest articles…” or “Hang tight, loading content.”

    3. Example: Skeleton Loading in SwiftUI

    Here’s a simple skeleton loader for your article rows:

    struct ArticleRowSkeleton: View {
        var body: some View {
            HStack {
                RoundedRectangle(cornerRadius: 8)
                    .fill(Color.gray.opacity(0.3))
                    .frame(width: 60, height: 60)
                VStack(alignment: .leading, spacing: 8) {
                    RoundedRectangle(cornerRadius: 4)
                        .fill(Color.gray.opacity(0.3))
                        .frame(width: 150, height: 16)
                    RoundedRectangle(cornerRadius: 4)
                        .fill(Color.gray.opacity(0.3))
                        .frame(width: 100, height: 12)
                }
            }
            .padding(.vertical, 8)
        }
    }
    

    And in your List:

    if vm.isLoading {
        ForEach(0..<5) { _ in
            ArticleRowSkeleton()
        }
    } else {
        // Your real content
    }
    

    4. Summary Checklist

    • Profile and optimize your data fetch.
    • Cache and show last data instantly.
    • Show skeleton loaders or placeholders, not just a spinner.
    • Communicate with the user if it’s slow.
    • Start loading as early as possible in the app lifecycle.

    If you want a more advanced skeleton loader or have questions about caching, let me know!

  21. User

    How do I use background threads for data loading in ios 16+?

  22. Assistant

    Great question!
    In iOS 16+ (and iOS 15+), the modern way to do background data loading in Swift is to use Swift Concurrency (async/await) with Task or Task.detached. This keeps your UI responsive and makes your code much easier to read and maintain than old-style GCD.


    How to Use Background Threads for Data Loading

    1. Use async/await in Your ViewModel

    Suppose you have a function that fetches articles from the network:

    class LatestViewModel: ObservableObject {
        @Published var articles: [Article] = []
        @Published var isLoading = false
    
        // Example async function for loading articles
        func load() async {
            isLoading = true
            defer { isLoading = false }
            do {
                // This runs on a background thread automatically
                let fetched = try await ArticleAPI.fetchArticles()
                // UI updates must be on the main thread
                await MainActor.run {
                    self.articles = fetched
                }
            } catch {
                // Handle error
                print("Error loading articles: \(error)")
            }
        }
    }
    
    • ArticleAPI.fetchArticles() should be an async function that does the network call.

    2. Call Your Async Function from the View

    In your SwiftUI view, use .task to call your async function.
    .task automatically runs the closure in the background.

    struct LatestListViewTest: View {
        @StateObject private var vm = LatestViewModel()
    
        var body: some View {
            List {
                // ... your list content ...
            }
            .task {
                await vm.load()
            }
        }
    }
    

    3. If You Need to Do Heavy Work (Parsing, etc.)

    If you have heavy work (like parsing a huge file), you can use Task.detached to explicitly run code off the main thread:

    func load() async {
        isLoading = true
        defer { isLoading = false }
        do {
            let fetched = try await Task.detached(priority: .background) {
                return try await ArticleAPI.fetchArticles()
            }.value
            await MainActor.run {
                self.articles = fetched
            }
        } catch {
            print("Error loading articles: \(error)")
        }
    }
    

    But for most network calls, just using async/await is enough—URLSession and most async APIs are already off the main thread.


    Summary

    • Use async/await for your data loading functions.
    • Use .task in your SwiftUI view to call them.
    • UI updates must be on the main thread (await MainActor.run { ... }).
    • For extra-heavy work, use Task.detached.

    This is the modern, safe, and recommended way to do background work in iOS 16+!

    If you want a concrete example with your own API, just ask!

  23. User

    Right now, in my NavigationView, I have a .task { await vm.load() } - is that async?

  24. Assistant

    Yes, your use of .task { await vm.load() } in your SwiftUI view is asynchronous and is the modern, recommended way to kick off async work (like network loading) in SwiftUI.

    How it works:

    • The .task modifier runs its closure asynchronously when the view appears.
    • If you use await inside the closure, SwiftUI will run that code on a background thread (not blocking the main thread/UI).
    • Your vm.load() function should be marked as async and do its work using async/await (e.g., using URLSession.shared.data(for:) or other async APIs).

    Example:

    struct MyView: View {
        @StateObject var vm = MyViewModel()
    
        var body: some View {
            NavigationView {
                // ... your content ...
            }
            .task {
                await vm.load() // This is async!
            }
        }
    }
    

    In your ViewModel:

    class MyViewModel: ObservableObject {
        @Published var data: [MyData] = []
    
        func load() async {
            // This is async, runs off the main thread
            let result = try? await MyAPI.fetchData()
            await MainActor.run {
                self.data = result ?? []
            }
        }
    }
    

    Summary

    • .task { await vm.load() } is async.
    • It does not block the UI.
    • It is the modern, recommended way to load data in SwiftUI (iOS 15+).

    Tip:
    If you want to show a loading indicator, set a @Published var isLoading = true before your network call and set it to false after, updating it on the main actor if needed.


    If you want a more detailed example or have a specific scenario, let me know!

  25. User

    I like the skeleton idea, but don't want to implement it just yet.

    What can I put on my screen before the ProgressView fires to show the state of my app?

  26. Assistant

    Great question!
    If you want to show something immediately (before your ProgressView appears), you have a few good options to make your app feel more responsive and branded, even before your data or loading state is set.


    1. App Logo or Branding

    Show your app’s logo, name, or a simple welcome message.
    This is a common approach and gives users instant feedback that the app is running.

    struct LaunchPlaceholder: View {
        var body: some View {
            VStack {
                Image("AppLogo") // Replace with your asset name
                    .resizable()
                    .frame(width: 100, height: 100)
                Text("Welcome to Newsly")
                    .font(.headline)
                    .padding(.top, 8)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color(.systemBackground))
        }
    }
    

    2. Custom Placeholder View

    Show a neutral placeholder, such as a colored background with a message:

    struct InitialPlaceholder: View {
        var body: some View {
            VStack {
                Text("Loading latest articles…")
                    .font(.title3)
                    .foregroundColor(.secondary)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color(.systemBackground))
        }
    }
    

    3. Combine with ProgressView

    You can combine a logo/message with a ProgressView for a more polished look:

    struct BrandedLoadingView: View {
        var body: some View {
            VStack(spacing: 24) {
                Image("AppLogo")
                    .resizable()
                    .frame(width: 80, height: 80)
                Text("Fetching the latest news…")
                    .font(.headline)
                ProgressView()
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color(.systemBackground))
        }
    }
    

    How to Use in Your Main View

    You can show this placeholder before your data loads or before isLoading is set:

    struct LatestListViewTest: View {
        @StateObject private var vm = LatestViewModel()
        @State private var hasAppeared = false
    
        var body: some View {
            NavigationStack {
                Group {
                    if !hasAppeared {
                        // Show placeholder immediately
                        LaunchPlaceholder()
                    } else if vm.isLoading {
                        // Show loading spinner
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                            .padding()
                    } else {
                        // Show your list
                        List { /* ... */ }
                    }
                }
                .task {
                    hasAppeared = true
                    await vm.load()
                }
            }
        }
    }
    

    Summary

    • Show a logo, app name, or welcome message as a placeholder.
    • Optionally combine with a ProgressView.
    • This gives users instant feedback and a branded experience, even before your loading state is set.

    You can always upgrade to a skeleton loader later!
    Let me know if you want a more advanced placeholder or animation ideas.

  27. User

    It still takes 5-10 seconds to be able to see my launch placeholder.

  28. Assistant

    This is a critical clue:
    If your launch placeholder (or any SwiftUI view) takes 5–10 seconds to appear before your data even starts loading, the problem is not with your loading logic or UI state.
    It’s likely happening before your SwiftUI view is even created.


    What’s Actually Happening?

    • If your app is cold-launching and you see a blank screen for several seconds before any SwiftUI view appears, this is almost always due to something blocking the main thread during app startup.
    • This is not a SwiftUI or ProgressView issue.
    • It’s likely something in your App struct, SceneDelegate, or an early synchronous operation (like a big file read, database migration, or synchronous network call) that’s blocking the main thread.

    How to Diagnose and Fix

    1. Check for Synchronous Work in App Startup

    • Look in your @main App struct (or AppDelegate/SceneDelegate if you use UIKit).
    • Are you doing any heavy work (database setup, file I/O, network calls) before your first view appears?
    • All heavy work should be async!

    2. Use Logging to Pinpoint the Delay

    Add print statements to see how long it takes for your view to appear:

    @main
    struct MyApp: App {
        init() {
            print("App init at", Date())
        }
        var body: some Scene {
            WindowGroup {
                ContentView()
                    .onAppear {
                        print("ContentView appeared at", Date())
                    }
            }
        }
    }
    
    • If there’s a big gap between App init and ContentView appeared, something is blocking startup.

    3. Check for Large Asset Loads or Database Migrations

    • Are you initializing a large database (Core Data, Realm, etc.) synchronously?
    • Are you loading big images or files in your App or ViewModel initializers?
    • Are you doing any synchronous network calls?

    All of these should be moved to background threads or made async.

    4. Use Xcode Instruments

    • Profile your app’s launch with Xcode Instruments (Time Profiler).
    • Look for long-running tasks on the main thread during launch.

    How to Fix

    • Move all heavy work to background threads using Task { ... }, DispatchQueue.global().async { ... }, or (preferably) async/await.
    • Show your placeholder view immediately in your SwiftUI hierarchy, and start loading data in .task or .onAppear.

    Example: Fast App Launch

    @main
    struct MyApp: App {
        var body: some Scene {
            WindowGroup {
                LaunchPlaceholder() // This appears instantly
                    .task {
                        // Start loading data here, async!
                    }
            }
        }
    }
    

    Summary Table

    SymptomLikely CauseSolution
    Blank screen before any viewSynchronous work on main threadMove to async/background thread
    ProgressView slow to appearView not created yetShow placeholder immediately
    Data slow to load after viewSlow network or parsingOptimize/caching/skeleton views

    If you want help debugging your specific startup code, paste your App struct and any startup logic here!


    TL;DR:

    Your placeholder should appear instantly. If it doesn’t, something is blocking the main thread before your SwiftUI view is created. Move all heavy startup work to background threads.

  29. User

    The time between app init and ContentView appearing was quite short. The longest amount of time was before App Init. How do I debug that?

  30. Assistant

    Excellent diagnosis!
    If the delay is before your @main App struct's init, then the issue is happening before your code even runs. This is rare, but it can happen due to:

    • App thinning or code signing issues
    • Large or corrupted asset catalogs
    • Large Info.plist or malformed configuration files
    • Unusually large or complex app binaries
    • iOS system-level delays (rare, but possible on simulators or old devices)
    • Third-party frameworks with heavy static initializers

    How to Debug Pre-App Startup Delays

    1. Test on a Real Device

    • Simulators can sometimes be much slower than real devices, especially on first launch after a build.
    • Always test on a real device to rule out simulator-specific issues.

    2. Check Your Asset Catalog

    • Large images or many images in your asset catalog can slow down app launch.
    • Try removing or reducing assets to see if launch time improves.

    3. Check Your Info.plist

    • Large or complex Info.plist files can slow down launch.
    • Remove unnecessary keys or large embedded data.

    4. Check for Large Embedded Resources

    • Do you have large files (videos, PDFs, databases) in your app bundle?
    • Try removing them temporarily and see if launch improves.

    5. Check for Static Initializers in Frameworks

    • Some third-party frameworks (especially those using Objective-C or C++) can run code before your app’s main function.
    • Try removing frameworks one by one to see if launch improves.

    6. Profile with Xcode Instruments: "App Launch" Template

    • Open Xcode > Product > Profile > Choose "App Launch" template.
    • This will show you what happens before your code runs.
    • Look for time spent in dyld (dynamic linker), asset loading, or other system calls.

    7. Check for App Thinning or Code Signing Issues

    • Sometimes, Xcode or the OS can take a long time to process the app binary, especially on first install.
    • Try deleting the app and reinstalling.
    • Try a clean build (Cmd+Shift+K), then rebuild and run.

    8. Check for Large Swift Packages or Embedded Frameworks

    • Large or complex Swift packages can increase binary size and launch time.
    • Try removing or disabling them temporarily.

    Summary Table

    Possible CauseHow to Check/Fix
    Large asset catalogRemove/reduce images, test launch time
    Large Info.plistSimplify, remove unnecessary keys
    Large embedded resourcesRemove large files, test launch time
    Third-party frameworksRemove frameworks, test launch time
    App thinning/code signingClean build, reinstall app
    Simulator vs. real deviceTest on real device
    System-level delaysReboot device, update iOS
    Profile with InstrumentsUse "App Launch" template to see pre-main activity

    What to Do Next

    1. Profile with Instruments to see what’s happening before main.
    2. Remove large assets/resources/frameworks one by one to isolate the cause.
    3. Test on a real device to rule out simulator issues.

    If you want, share your app’s structure (assets, frameworks, etc.) and I can help you pinpoint likely causes!


    TL;DR:

    If the delay is before your code runs, it’s almost always due to large assets, resources, or frameworks. Profile with Instruments and try removing assets/frameworks to isolate the cause. Test on a real device!

    Let me know what you find!

  31. User

    I have 4 custom fonts installed. Are they slowing things down?

  32. Assistant

    Great question!
    Custom fonts can add a small amount of overhead to app launch, but in almost all cases, 4 custom fonts (even with several weights/styles each) will not cause a 5–10 second delay before your app’s code runs.

    When do custom fonts cause a problem?

    • If you have dozens or hundreds of font files, or
    • If your font files are very large (multi-megabyte, e.g. CJK fonts with thousands of glyphs), or
    • If the font files are corrupted or malformed.

    Typical impact

    • For most apps, a handful of custom fonts adds milliseconds to launch time, not seconds.
    • iOS loads fonts efficiently and only when needed.

    How to check if fonts are the cause

    • Temporarily remove the custom fonts from your project and run the app. If the launch time improves dramatically, then fonts are a factor.
    • If there’s no change, fonts are not the issue.

    What else to check

    • If you’re using a font very early (e.g., in your launch screen storyboard or in your very first SwiftUI view), it will be loaded at launch, but this is still fast for a few fonts.
    • If you have a LaunchScreen.storyboard that uses custom fonts, try switching it to system fonts as a test.

    Summary Table

    Number of FontsTypical Impact on LaunchShould You Worry?
    1–10Negligible (ms)No
    10–50Slight (ms–100ms)Rarely
    50+ or hugePossible (100ms+)Maybe

    Bottom Line

    • 4 custom fonts will not cause a 5–10 second launch delay.
    • If you want to be sure, remove them temporarily and test.
    • The cause of your delay is almost certainly elsewhere (see previous answer for more likely culprits).

    If you want to share your font file sizes or how you’re using them, I can give more specific advice!

  33. User

    I'm testing the app on a iphone that is connecting to xcode over wifi. How can I do time profiling?

  34. Assistant

    Great question!
    Time profiling is best done with your device connected via USB, but you can still do some profiling over Wi-Fi. Here’s how to get the most accurate results:


    1. For Best Results: Use a USB Cable

    • Connect your iPhone to your Mac with a USB cable.
    • This is much faster and more reliable for profiling, especially for launch-time analysis.
    • Xcode and Instruments can stream data in real time with minimal lag.

    2. If You Must Use Wi-Fi:

    • Make sure your device and Mac are on the same Wi-Fi network.
    • Go to Xcode > Window > Devices and Simulators, select your device, and ensure “Connect via network” is checked.
    • Be aware: Profiling over Wi-Fi can be slower and less reliable, especially for launch-time events.

    3. How to Profile App Launch Time

    A. Using Xcode Instruments

    1. Open Xcode.
    2. Product > Profile (or press ⌘I) with your device selected as the run target.
    3. Xcode will build your app and open Instruments.
    4. Choose the “App Launch” template (or “Time Profiler” for general performance).
    5. Click Record (red button) in Instruments.
    6. Watch for the timeline: You’ll see what happens before and after your app’s main function.
    7. Look for long blocks before your code runs (these are pre-main events).

    B. Using Xcode’s Debug Navigator

    • Run your app from Xcode.
    • Open the Debug Navigator (⌘7).
    • Watch the CPU and memory graphs for spikes or stalls during launch.

    4. Tips for Accurate Profiling

    • Always prefer USB for launch profiling. Wi-Fi can introduce delays unrelated to your app.
    • Profile on a real device, not the simulator.
    • Profile a Release build (not Debug) for realistic performance.
    • Restart your device before profiling to clear out any background processes.

    5. What to Look For

    • In the App Launch template, look for:
      • dyld (dynamic linker) time
      • Asset loading
      • Pre-main time (before your code runs)
    • In Time Profiler, look for:
      • Long-running functions
      • Main thread blocks

    Summary Table

    ConnectionAccuracyRecommended For Profiling?
    USBHighYes
    Wi-FiMediumOnly if USB not possible

    If You See Delays in Pre-main

    • It’s almost always due to large assets, frameworks, or system-level issues.
    • See previous answers for how to debug and fix.

    If you need step-by-step screenshots or help interpreting Instruments results, just ask!

  35. User

    My console shows this:

    load_eligibility_plist: Failed to open /Users/dfdc/Library/Developer/CoreSimulator/Devices/9D7DB54B-7771-46B8-80C2-AA995183D0A1/data/Containers/Data/Application/AAE023A8-4B92-4C71-AF4E-0F0B136B2CB9/private/var/db/eligibilityd/eligibility.plist: No such file or directory(2)

  36. Assistant

    Great observation!
    The message:

    load_eligibility_plist: Failed to open .../eligibility.plist: No such file or directory(2)
    

    is a CoreSimulator (iOS Simulator) log message. It means the simulator is looking for a file related to device eligibility (used internally by iOS for things like Apple Pay, Face ID, etc.) and can't find it. This is not an error in your app and is not related to your app's launch performance.


    What does it mean?

    • This is a benign, internal message from the iOS Simulator.
    • It happens because the simulator doesn't always create every system file that a real device would have.
    • It is safe to ignore unless you are developing low-level system features (which you are not).

    Does it affect my app?

    • No. It does not affect your app's performance, launch time, or functionality.
    • It is not the cause of your slow launch.

    What should I do?

    • Ignore it. It is just noise in the console.
    • If you want a cleaner console, you can filter out system messages in Xcode's console by clicking the filter icon and selecting "My Code Only".

    If you see this on a real device:

    • It's still not a problem for your app, but if you see other issues, let Apple know via Feedback Assistant.

    Summary

    • This message is not related to your app's slow launch.
    • It is a harmless simulator/system log.
    • Focus on other causes for your launch delay (see previous answers).

    If you have other console messages or want to share your Instruments results, I can help interpret them!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.