我想要的是为一些符合某些协议的NSObjectProtocol自动实现委托方法,但我努力了,但没有做到。
下面是演示
更新以获得更准确
=========================================================================
我得到了一个协议PagedLoadable来获取collectionView所需的信息,然后是extension NSObjectProtocol where Self: Delegatable,对象实现PagedLoadable的自动配置
protocol PagedLoadable {
var count: Int { get }
}
protocol Delegatable: UICollectionViewDelegate, UICollectionViewDataSource {
}
extension PagedLoadable where Self: Delegatable {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return count
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = UICollectionViewCell()
return cell
}
}
class vc: UIViewController {
}
extension vc: PagedLoadable {
var count: Int {
return 1
}
}
extension vc: Delegatable {
}发布于 2015-11-24 14:28:37
创建协议
//类SurveyDownloadHandler
protocol SurveyDownloadHandlerDelegate {
func surveyDownloadSuccessfully(notiExpireRemainingTime : Int)
func surveyDownloadConnectionFail()
}
class SurveyDownloadHandler: NSObject {
var delegate: SurveyDownloadHandlerDelegate! = nil
}//方法回调A类delegate.surveyDownloadSuccessfully(notiExpireRemainingTime)
// A类
class A : UIViewController,SurveyDownloadHandlerDelegate{
let surveyDownloadHandlerObject : SurveyDownloadHandler = SurveyDownloadHandler()
@IBAction func onTapClick(sender: AnyObject) {
self.surveyDownloadHandlerObject.delegate = self
self.surveyDownloadHandlerObject.startDownloadingSurvey()
}
}
func surveyDownloadSuccessfully(notiExpireRemainingTime : Int)
{
}
func surveyDownloadConnectionFail()
{
}
}发布于 2015-11-24 15:09:23
您正在尝试实现对协议的扩展,但继承除外。经过一些实验后,我可以用下面的方法来消除你的错误。
//: [Next](@next)
protocol PagedLoadable {
var count: Int { get }
}
protocol Delegatable: UICollectionViewDelegate, UICollectionViewDataSource {
}
extension Delegatable {
}
//Removed since code will not be able to resolve dependency
extension PagedLoadable /*where Self: Delegatable*/ {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return count
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = UICollectionViewCell()
return cell
}
}//一种方式是
class vc: UIViewController,PagedLoadable, Delegatable {
var count: Int {
return 1
}
}//或者您也可以这样做
extension vc: PagedLoadable, Delegatable {
var count: Int {
return 1
}
}https://stackoverflow.com/questions/33886543
复制相似问题