Home > Enterprise >  Broken .searchable() modifier in SwiftUI with Xcode
Broken .searchable() modifier in SwiftUI with Xcode

Time:08-11

I noticed that when I create a simple searchable list in my old iPadOS/iOS App with the latest Xcode 14 Beta (at least beta no 4 and 5), the text deletes itself. I'm not sure if this happened with old versions of Xcode and iPadOS Betas (just noticed with iPadOS beta 4 and 5, too).

I created a new project with just this few lines of code:

@main
struct MyApp: SwiftUI.App {
    
@State private var strings = ""
    
    var body: some Scene {
        WindowGroup {
            NavigationStack {
                List {
                    Text("Item 1")
                    Text("Item 2")
                    Text("Item 3")
                }
                .searchable(text: $strings)
            }
        }
    }
}

If I build and execute this in a new project, it works properly. BUT if I try to execute that exact code in my old app (created with Xcode 11) I get this:

enter image description here

As we can see, once I write a single letter in the SearchTextField, it deletes itself. I cannot debug this, because this is all the code my app is running, and I cannot send to Apple any Feedback because when I create a new project it works correctly.

Does anyone know if this error happens because an incorrect configuration or something similar?

[iPad Pro 12.9, Swift 5.6, SwiftUI 4.0, Xcode 14 Beta 5]

CodePudding user response:

See my example below:

struct ContentView: View {
    
    @State private var searchText = ""
    let strings: [String] = ["1", "2", "3"]
    
    var body: some View {
        
        NavigationView {
            List(strings, id: \.self) {
                Text($0)
            }.searchable(text: $searchText)
        }
    }
}

This issue either has to do with the custom NavigationStack you are using or the lack of a list. Without more details it would be impossible to tell. I would suggest working backwards to a state that works and then move forward one item at a time to see where it breaks. My example above works to have a search bar and a list of items (no filter functionality yet though).

Hope this helps!

CodePudding user response:

Solution

The problem was caused because a Binding extension, added to extend some features to SwiftUI. This is the snippet that was causing the issue (please, DO NOT USE this snippet):

extension Binding: Equatable where Value: Equatable {
    public static func == (lhs: Binding<Value>, rhs: Binding<Value>) -> Bool {
        return lhs.wrappedValue == rhs.wrappedValue
    }
}

extension Binding: Hashable where Value: Hashable {
    public func hash(into hasher: inout Hasher) {
        self.wrappedValue.hash(into: &hasher)
    }
}

I had a lot of work searching over the more than 50.000 lines of code of my app, created a new target and added manually files to inspect what was causing the error. I hope this helps someone else.

  • Related