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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.