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

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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.