Accessing protocol property in Swift class

大兔子大兔子 提交于 2020-01-04 05:33:35

问题


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?


来源:https://stackoverflow.com/questions/34730672/accessing-protocol-property-in-swift-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!