Accessing protocol property in Swift class

2019-07-09 04:45发布

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?

2条回答
聊天终结者
2楼-- · 2019-07-09 05:00

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
查看更多
虎瘦雄心在
3楼-- · 2019-07-09 05:14

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

var delegate: PinsArray?
查看更多
登录 后发表回答