swift protocol的幾種形式

三個關注點:一、形式;二、實現方式;三、使用方式;app

 

1、基本形式:

 形式:內部無泛型類型;less

實現:只需指定類型和實現相應的功能便可;函數

使用:能夠用在其餘類型出現的任何地方;ui

 

protocol Response {this

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

    var _metrics: AnyObject? { get set }code

    mutating func add(_ metrics: AnyObject?)orm

}ci

 

Protocols as Typesrem

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

實現類提供:函數的具體實現和存儲變量;

對於變量,提供同名的存儲變量便可;

 

2、普通泛型形式:

形式:內部無高階類型,只包含普通泛型類型;

實現:只需指定類型和實現相應的功能便可;

使用:只能用做泛型類型的約束;

 

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()

}

}

 

3、monad形式:

形式:內部有包含泛型的高階類型,包含類型構造器,是低階類型與高階類型相互轉換和引用的橋樑;

使用:只能用做泛型類型的約束;

實現:

一、指定類型和實現相應;

二、對泛型自己進行擴展,實現構造類型變量的賦值;

三、對構造類型進行擴展,實現更多的功能;

四、實現爲一個泛型類型?

 

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)

        }

    }

}

 

4、內部實現依賴於其它協議

 形式:關聯類型有其它協議約束

實現:

一、關聯類型協議類型的實現:

二、關聯類型所定義的變量的構造;

三、主協議的實現(引用關聯類型的協議的實現);

 

本質:先實現依賴的協議,而後實現本協議

 

使用:同二

 

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)

    }

}

相關文章
相關標籤/搜索