UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How do I pass a generic struct?

Forums > SwiftUI

I'm having difficulty getting to understand generic types in Swift, and in particular in SwiftUI. I have a struct

struct Option<T: Hashable>: Hashable  {
    let name: String
    let value: T

    init (_ name: String, _ value: T) {
        self.name = name
        self.value = value
    }

}

var options: [Option<Int>] = [ Option("first", 1), Option("second", 2), Option("third", 3) ]
ShowOptions(options: options)

T may be one of a variety of types. ShowOptions is a View which will display the names (and, in due course, allow one to be selected and pass out its value property).

struct ShowOptions: View {
    var options: [Option<AnyHashable>]

    var body: some View {
        VStack {
            Spacer()
            ForEach (options, id: \.self) { opt in
                Text(opt.name)
            }
            Spacer()
        }
    }
}

I get an error because <Int> isn't the same as <AnyHashable>.

I expect I'm just not grasping something important about generics. Any tips?

Jeremy

2      

Never mind - I realised my problem. I need to alter ShowOptions.

struct ShowOptions<T: Hashable>: View {
  var options: [Option<T>]
  ...
 }

Live and learn.

Jeremy

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.