Accessing protocol property in Swift class

2019-07-09 05:00发布

问题:

I am trying to use a protocol to pass an array from one class to another.

protocol PinsArray {
var dataArray: [LocationPost] {get set}
}

When I am trying to create a delegate in class, which should receive it does not work. I cannot access the property

var delegate = PinsArray.self

Like this:

delegate.dataArray

It says that "instance member 'dataArray' cannot be used on type PinArray"

So what do I do wrong?

回答1:

You are assigning the type of PinsArray to delegate instead of assigning an instance of a class that conforms PinsArray. You would need to implement an a class that conforms to PinsArray and assign an instance of that class to delegate. See the following example:

class SomeClass: PinsArray {
    var dataArray: [LocationPost]
    // ...
}

You would use the class above to create an instance of an object that conforms to PinsArray.

var delegate = SomeClass()

Then you could use:

delegate.dataArray


回答2:

I declared the delegate with a typo, it should be like this:

var delegate: PinsArray?