18.面向协议编程

/// 前缀类型
struct JD {
var base: Base
init(_ base: Base) {
self.base = base
}
}

/// 利用协议扩展前缀属性
protocol JDCompatible {}
extension JDCompatible {
static var jd: JD.Type {
set {}
get { JD.self }
}
var jd: JD {
set {}
get { JD(self) }
}
}

/// 给字符串扩展功能
// 让String拥有jd前缀属性
extension String: MJCompatible {}
extension NSString: MJCompatible {}

// 给String.jd、String().jd前缀扩展功能
extension JD where Base: ExpressibleByStringLiteral {
var numberCount: Int {
var count = 0
for c in (base as! String) where ("0"..."9").contains(c) {
count += 1
}
return count
}
}

利用协议实现类型判断

protocol ArrayType {}
extension Array: ArrayType {}
extension NSArray: ArrayType {}

//var ttt: ArrayType.Type
//ttt = Array.self
//ttt = NSArray.self
//ttt = NSMutableArray.self

func isArrayType(_ type: Any.Type) -> Bool {
type is ArrayType.Type
}

print( isArrayType( [Int].self ) )
print( isArrayType( [Double].self ) )
print( isArrayType( [Any].self ) )
print( isArrayType( NSArray.self ) )
print( isArrayType( NSMutableArray.self ) )
print( isArrayType( String.self ) )

你可能感兴趣的:(18.面向协议编程)