1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| import Foundation
/// 前缀类型 //前缀类型 struct Swifter<Base> { let base: Base init(_ base: Base) { self.base = base } } //利用协议扩展属性 protocol SwifterProtocol {}
extension SwifterProtocol { var swifter: Swifter<Self> { set { } get { return Swifter(self) } } static var swifter: Swifter<Self>.Type { set { } get { Swifter<Self>.self } } }
//给字符串扩展功能 extension String: SwifterProtocol {} extension NSString: SwifterProtocol {} //extension NSMutableString: SwifterProtocol {} //给Person扩展功能 class Person{} extension Person: SwifterProtocol {}
// 扩展功能 extension Swifter where Base: ExpressibleByStringLiteral { var numberCount: Int { var count = 0 for c in (base as! String) where ("0"..."9").contains(c) { count += 1 } return count } static func test() { print("test") } mutating func run() { // self.base = "run" } }
extension Swifter where Base: Person { func run() { print("跑") } }
print("123ooo123".swifter.numberCount) Person().swifter.run()
String.swifter.test()
var abc = "123" var def: NSMutableString = "456" abc.swifter.run() print(abc) def.swifter.run()
/////////////////////////
protocol ArrayType { } extension Array: ArrayType{} extension NSArray: ArrayType{} extension String: ArrayType{} func isArrayType(_ type: Any.Type) -> Bool { type is ArrayType.Type }
print(isArrayType([Int].self)) print(isArrayType([Any].self)) print(isArrayType(NSArray.self)) print(isArrayType(NSMutableArray.self)) print(isArrayType(String.self))
|