Search code examples
swiftassociated-types

Tuple type with hashable items


I'm trying to make a tuple type which has a Hashable item & an Any item, & use it in a custom initializer for Dictionary. However, Swift won't use Hashable in this way, & I'm stuck for an alternative. I don't want to restrict the dictionaries I can create to just using Strings as keys.

protocol CollectionInitializeable {
    associatedtype T
    init(items: [T])
}

extension Dictionary: CollectionInitializeable {

    typealias T = (Hashable, Any) // not allowed

    init(items: [T]) {

        self.init()
        // etc...
    }
}

Solution

  • Update:

    This is unnessary now, thanks to Dictionary.init(uniqueKeysWithValues:) and Dictionary.init(_:uniquingKeysWith:)

    Original Post:

    Are you looking for something like this?

    protocol CollectionInitializeable {
        associatedtype T
        init<C: Collection>(items: C) where C.Iterator.Element == T
    }
    
    extension Dictionary: CollectionInitializeable {
        typealias T = Iterator.Element
        
        init<C: Collection>(items c: C)
        where C.Iterator.Element == T {
            self.init()
            for (key, value) in c {
                self[key] = value
            }
        }
    }
    
    let a = [
        (key: 1, value: "a"),
        (key: 2, value: "b"),
        (key: 3, value: "c")
    ]
    
    print(Dictionary(items: a))