swift protocol的几种形式

三个关注点:1、形式;2、实现方式;3、使用方式;

 

一、基本形式:

 形式:内部无泛型类型;

实现:只需指定类型和实现相应的功能即可;

使用:可以用在其他类型出现的任何地方;

 

protocol Response {

    /// The task metrics containing the request / response statistics.

    var _metrics: AnyObject? { get set }

    mutating func add(_ metrics: AnyObject?)

}

 

Protocols as Types

Protocols don’t actually implement any functionality themselves. Nonetheless, any protocol you create will become a fully-fledged type for use in your code.

Because it’s a type, you can use a protocol in many places where other types are allowed, including:

  • As a parameter type or return type in a function, method, or initializer
  • As the type of a constant, variable, or property
  • As the type of items in an array, dictionary, or other container

实现类提供:函数的具体实现和存储变量;

对于变量,提供同名的存储变量即可;

 

二、普通泛型形式:

形式:内部无高阶类型,只包含普通泛型类型;

实现:只需指定类型和实现相应的功能即可;

使用:只能用作泛型类型的约束;

 

Protocol 'TransformType' can only be used as a generic constraint because it has Self or associated type requirements

 

public protocol TransformType {

associatedtype Object

associatedtype JSON

 

func transformFromJSON(_ value: Any?) -> Object?

func transformToJSON(_ value: Object?) -> JSON?

}

 

open class DataTransform: TransformType {

public typealias Object = Data

public typealias JSON = String

 

public init() {}

 

open func transformFromJSON(_ value: Any?) -> Data? {

guard let string = value as? String else{

return nil

}

return Data(base64Encoded: string)

}

 

open func transformToJSON(_ value: Data?) -> String? {

guard let data = value else{

return nil

}

return data.base64EncodedString()

}

}

 

三、monad形式:

形式:内部有包含泛型的高阶类型,包含类型构造器,是低阶类型与高阶类型相互转换和引用的桥梁;

使用:只能用作泛型类型的约束;

实现:

1、指定类型和实现相应;

2、对泛型本身进行扩展,实现构造类型变量的赋值;

3、对构造类型进行扩展,实现更多的功能;

4、实现为一个泛型类型?

 

public protocol ReactiveCompatible {

    /// Extended type

    associatedtype CompatibleType

    /// Reactive extensions.

    var rx: Reactive<CompatibleType> { get set }

}

 

extension ReactiveCompatible {

 

    /// Reactive extensions.

    public var rx: Reactive<Self> {

        get {

            return Reactive(self)

        }

        set {

            // this enables using Reactive to "mutate" base object

        }

    }

}

 

extension NSObject: ReactiveCompatible { }

 

//—————————————————————

 

public final class Kingfisher<Base> {

    public let base: Base

    public init(_ base: Base) {

        self.base = base

    }

}

 

public protocol KingfisherCompatible {

    associatedtype CompatibleType

    var kf: CompatibleType { get }

}

 

public extension KingfisherCompatible {

    public var kf: Kingfisher<Self> {

        return Kingfisher(self)

    }

}

 

extension Kingfisher where Base: Image {

    fileprivate(set) var animatedImageData: Data? {

        get {

            return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data

        }

        set {

            objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

        }

    }

}

 

四、内部实现依赖于其它协议

 形式:关联类型有其它协议约束

实现:

1、关联类型协议类型的实现:

2、关联类型所定义的变量的构造;

3、主协议的实现(引用关联类型的协议的实现);

 

本质:先实现依赖的协议,然后实现本协议

 

使用:同二

 

public protocol Sequence {

    associatedtype Iterator : IteratorProtocol

    

    public func makeIterator() -> Self.Iterator

    

    // ...

}

 

public protocol IteratorProtocol {

    associatedtype Element

    

    public mutating func next() -> Self.Element?

}

 

 

struct _Iterator: IteratorProtocol {

    var children: Mirror.Children

    

    init(obj: Any) {

        children = Mirror(reflecting: obj).children

    }

    

    mutating func next() -> String? {

        guard let child = children.popFirst() else { return nil }

        return "\(child.label.wrapped) is \(child.value)"

    }

}

 

protocol Sequencible: Sequence { }

 

extension Sequencible {

    func makeIterator() -> _Iterator {

        return _Iterator(obj: self)

    }

}

 

posted @ 2019-03-11 18:51  zzfx  阅读(2123)  评论(0编辑  收藏  举报