为什么说swift是面向协议编程--草稿?

为什么说swift是面向协议编程

public protocol ReactiveCompatible {

/// Extended type

associatedtype CompatibleType

/// Reactive extensions.

static var rx: Reactive<CompatibleType>.Type { get set }

/// Reactive extensions.

var rx: Reactive<CompatibleType> { get set }

}

extension ReactiveCompatible {

/// Reactive extensions.

public static var rx: Reactive<Self>.Type {

get {

return Reactive<Self>.self

}

set {

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

}

}

/// Reactive extensions.

public var rx: Reactive<Self> {

get {

return Reactive(self)

}

set {

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

}

}

}

protocol Response {

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

var _metrics: AnyObject? { get set }

mutating func add(_ metrics: AnyObject?)

}

其实像 Ruby 中的 Mix-in 或 Trait可以实现类似的功能,这里不展开讨论了。

当然会有人说,面向协议编程,这里的 protocol 不就是 Java 中的 interface 吗,对,也不对。Java 中的 interface,更多的功能是处理类型信息,更像是多态的效果,然而并没有提供代码的复用机制,因为拥有相同接口的不同的类,即使他们的接口实现都相同,也必须同时实现这个接口,于是,重复代码又出现了!

在 Swift 2.0 之后,我们可以使用 extension 为 protocol 添加默认的实现,也就是说,在大多数情况下,我们使用这种低耦合的方式,让你的类站出来说,我要遵循 XXX 协议,然后,就完成了!

http://www.futantan.com/2016/03/03/程序员的懒惰与面向协议编程-POP/

"A protocol defines a blueprint of methods, properties… The protocol can then be adopted by a class, structure, or enumeration" - Apple