EvGeniy Ilyin
EvGeniy Ilyin

Reputation: 1929

var in protocol as specific protocol

How to describe a variable in a protocol on swift any type, but supports a specific protocol

Something like this

protocol MyProtocol: class {
    var itemsList: AnyObject where Collection { get } // AnyObject supports a Collection protocol
}

Upvotes: 1

Views: 97

Answers (1)

BallpointBen
BallpointBen

Reputation: 13750

Maybe you want:

protocol MyProtocol: class {
    associatedtype T: Collection
    var itemsList: T { get }
}

If you want T to definitely be an object as well (not a struct) then you must wait for this proposal to make it into the language.

If you want a class to satisfy this protocol with T unspecified in the class's definition, make the class generic.

class C<T: Collection>: MyProtocol {
    let itemsList: T

    init(_ itemsList: T) {
        self.itemsList = itemsList
    }
}

let x = C([1,2,3])

Upvotes: 2

Related Questions