Teenenggr
Teenenggr

Reputation: 91

Generic issue while creating array in Swift

Here is protocol I am using,

public protocol PValidationCondition: Equatable {
    associatedtype T
    func isValid(value: T) -> Bool
    func errorMessage() -> String
}

This is model I am using:

struct PValidationElementWithConditions<T: PValidationCondition> {
    let validationElement: PValidationElement
    var conditions: [T] = []
}

But I would like to store the multiple object in array like the following:

var validationElementsWithConditions: [String: PValidationElementWithConditions] = [:]

But I am getting the following error:

"Cannot convert value of type '[String : PValidationElementWithConditions<_>]' to specified type '[String : PValidationElementWithConditions]'"

Upvotes: 2

Views: 86

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

This is incorrect

[String: PValidationElementWithConditions]

you have to do

[String: PValidationElementWithConditions<Type>]

where Type conforms to PValidationCondition & Equatable it's clear from the error here that it needs a paramter

PValidationElementWithConditions<_>

//

extension String  : PValidationCondition { 

    public func isValid(value: String) -> Bool {

        return true
    }

    public func errorMessage() -> String {

        return ""
    }

    public typealias T = String 

}

With

var validationElementsWithConditions: [String: PValidationElementWithConditions<String>] = [:]

Upvotes: 3

Abizern
Abizern

Reputation: 150595

Because it's generic, you need to specify the type T in the declaration. For example:

var validationElementsWithConditions: [String: PValidationElementWithConditions<String>] = [:]

Upvotes: 1

Related Questions