ios – How to accept any variable type that can be used in SwiftUI Text view


I’m trying to create a reusable component for presenting a Swift collections OrderedSet into a SwiftUI List with delete, move and add handlers.

I would like to be able to pass in an OrderedSet of any type that can be used directly as interpolated string, for example Text("hello \(myGenericTypeLikeAStringIntOrFloat) world").

I’ve been trying to find a protocol that can help me define these generic types and thought perhaps the ExpressibleByStringInterpolation could help here but I think thats only used to create your own types that can be used in SwiftUI Text views.

The error I’m getting on the Text("\(item)") line is No exact matches in call to instance method 'appendInterpolation'.

Is there a way to adjust my OrderedSet to only accept items that can be used in Text views?

Here’s a stripped down example that hopefully explains it better.


import SwiftUI
import OrderedCollections


struct ReusableListView<Element: Hashable>: View {
    
    @Binding var set: OrderedSet<Element>
    
    @State private var multiSelection: Set<String> = []
    
    init(_ set: Binding<OrderedSet<Element>>) {
        self._set = set
    }
    
    var body: some View {
        Section {
            List(selection: $multiSelection) {
                ForEach(set, id: \.self) { item in
                    Text("\(item)")
                }
                .onDelete { indexSet in
                    set.elements.remove(atOffsets: indexSet)
                }
            }
        }
    }
}


@main
struct MyApp: App {
    
    @State private var setWithStrings: OrderedSet<String> = ["hello", "world"]
    @State private var setWithInts: OrderedSet<Int> = [1, 2, 3]
    
    var body: some Scene {
        
        WindowGroup {
            ReusableListView($setWithStrings)
            ReusableListView($setWithInts)
        }
    }
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img