关于protocol的一些问题及解决办法

使用代理模式的时候需要用到protocol,有的时候会用到optional可选方法

如果直接这样写肯定会报错

```swift

protocol WaterFallFlowLayoutDatasource{

optional func waterFallFlowLayout(numberOfColumnInSection section:Int)-》Int

}

```

报错: 'optional' can only be applied to members of an @objc protocol

这里的解决方法是在protocol前面加上@objc关键字

像这样

```swift

@objc protocol WaterFallFlowLayoutDatasource

```

但是如果要使用自定义结构体作为返回值的时候就就会又出现新的问题:

```swift

public struct EdgeSpace {

public var vertical: CGFloat

public var horizontal: CGFloat

public init(vertical: CGFloat, horizontal: CGFloat){

self.horizontal = horizontal

self.vertical = vertical

}

}

@objc protocol WaterFallFlowLayoutDatasource{

optional func waterFallFlowLayout(insetForSectionOfIndex section:Int)->EdgeSpace

}

```

会报错:Method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C

这里可以这样来解决

```swift

public struct EdgeSpace {

public var vertical: CGFloat

public var horizontal: CGFloat

public init(vertical: CGFloat, horizontal: CGFloat){

self.horizontal = horizontal

self.vertical = vertical

}

}

protocol WaterFallFlowLayoutDatasource{

//这里是必须实现的方法

func waterFallFlowLayout(viewAtIndexPath indexPath:NSIndexPath)->UIView

//    这里是可选方法

func waterFallFlowLayout(insetForSectionOfIndex section:Int)->EdgeSpace

}

//在这里实现一下可选方法的默认值

extension WaterFallFlowLayoutDatasource{

func waterFallFlowLayout(insetForSectionOfIndex section:Int)->EdgeSpace{return EdgeSpace(vertical: 5, horizontal: 5)}

}

```

这样就解决问题了

你可能感兴趣的:(关于protocol的一些问题及解决办法)