参照RxSwift写的命名空间
方法一:
/**
/// A type that has reactive extensions.
public protocol ReactiveCompatible {
/// Extended type
associatedtype ReactiveBase
@available(*, deprecated, message: "Use `ReactiveBase` instead.")
typealias CompatibleType = ReactiveBase
/// Reactive extensions.
static var rx: Reactive<ReactiveBase>.Type { get set }
/// Reactive extensions.
var rx: Reactive<ReactiveBase> { get set }
}
*/
protocol MZCompatibleProtocol {
associatedtype T
static var mz: MZCompatible<T>.Type { get set }
var mz: MZCompatible<T> { get }
}
/**
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
}
}
}
*/
extension MZCompatibleProtocol {
public static var mz: MZCompatible<Self>.Type {
get {
return MZCompatible<Self>.self
}
set { }
}
public var mz: MZCompatible<Self> {
get {
return MZCompatible<Self>(base: self)
}
set { }
}
}
/**
public struct Reactive<Base> {
/// Base object to extend.
public let base: Base
/// Creates extensions with base object.
///
/// - parameter base: Base object.
public init(_ base: Base) {
self.base = base
}
}
*/
public struct MZCompatible<Base> {
/// Base object to extend.
public let base: Base
/// Creates extensions with base object.
///
/// - parameter base: Base object.
public init(base: Base) {
self.base = base
}
}
import class Foundation.NSObject
/// Extend NSObject with `mz` proxy.
extension NSObject: MZCompatibleProtocol { }
方法二:
/// 前缀
struct MZ<Base> {
var base: Base
init(_ base: Base) {
self.base = base
}
}
/// 利用协议扩展前缀
/// 协议扩展支持提供默认实现, 方便使其他类型支持前缀
protocol MZCompatible { }
extension MZCompatible {
// 类型计算属性
static var mz: MZ<Self>.Type {
set { }
get { MZ<Self>.self }
}
// 实例计算属性
var mz: MZ<Self> {
set { }
get { MZ(self) }
}
}
/// 给字符串扩展功能
extension String: MZCompatible { }
extension MZ where Base == String {
var upperCount: Int {
var count = 0
for c in base where ("A"..."Z").contains(c) {
count += 1
}
return count
}
}
使用:
对UIColor进行扩展
import UIKit
extension MZCompatible where Base: UIColor {
/// 获取随机颜色
static func getRandomColor() -> UIColor {
return UIColor(red: getArc4random(), green: getArc4random(), blue: getArc4random(), alpha: 1)
}
/// 获取随机数
private static func getArc4random() -> CGFloat {
return CGFloat(arc4random_uniform(256)) / 255.0
}
}
调用:
view.backgroundColor = UIColor.mz.getRandomColor()
网友评论