Swfit 优雅的自定义方法
struct
struct XQ<T> {
var type : T;
init(_ type: T) {
self.type = type
}
}
extension String {
var xq: XQ<String> {
set {}
get { XQ(self) }
}
static var xq: XQ<String>.Type {
set {}
get { XQ<String>.self }
}
}
extension XQ where T: ExpressibleByStringLiteral {
var length: Int {
return (type as! String).count;
}
static func isNull(_ string: String) {
// ...
}
}
let len = "A".xq.length
String.xq.isNull("111")
struct
class Car { }
extension Car {
var xq: XQ<Car> { XQ(self) }
}
extension XQ where T: Car {
func run() {}
mutating func stop() {}
}
Car().xq.run()
Any
extension XQ where T: Any {
func test() {
//...
}
}
Car().xq.test()
let str = "2222"
str.xq.test()
思路来源《小码哥教育》