TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SwiftUI ForEach raises error - Type 'any Storage' cannot conform to 'Hashable'

Forums > SwiftUI

How do I make this work? Rather than duplicating the MenuItem struct, I would like to be able to pass in any object conforming to Storage If I change 'var items: [Storage]' to just [Wallet] or [Bank] it works fine. But when it is [Storage], ForEach complains I'm new to Swift and trying hard to understand Hashable to resolve this issue but I need help.

protocol Storage { var index: Int { get } var name: String { get } // ... }

struct Bank: Storage, Hashable { let index: Int let name: String // ...

func hash(into hasher: inout Hasher) {
    hasher.combine(index)
}

}

struct Wallet: Storage, Hashable { let index: Int let name: String // ...

func hash(into hasher: inout Hasher) {
    hasher.combine(index)
}

}

struct MenuItem: View { // I need this to except objects conforming to the Storage protocol var items: [Storage]

var body: some View {
    VStack(spacing: 0) {
        // ... Type 'any Storage' cannot conform to 'Hashable'

        ForEach(items, id: \.self) {item in
            // ... This thows the error
        }
    }
}

}

var banks = [Bank]() var wallets = [Wallet]()

1      

protocol Storage: Hashable { 
  var index: Int { get } 
  var name: String { get } // ...
}

does not work?

1      

No. I did try that. I get the same error

1      

@Bnerd  

Your Storage is a protocol, using var items: [Storage], is like saying items is of an array of Storage Protocols.

1      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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.