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)
}
}
swift protocol的幾種形式