第一種實現方式: 原理: 1.泛型類 2.泛型協議 3.協議拓展bash
// 定義泛型類
public final class YKKit<Base> {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
// 定義泛型協議
public protocol YKKitCompatible {
associatedtype CompatibleType
var yk: CompatibleType { get }
}
// 協議的擴展
public extension YKKitCompatible {
public var yk: YKKit<Self>{
get { return YKKit(self) }
}
}
// 實現命名空間yk
extension String: YKKitCompatible {}
// String命名空間yk中的函數
extension YKKit where Base == String {
// MARK: - Localized
/// 國際化值
public var localized: String {
return NSLocalizedString(base, comment: "")
}
}
// 使用
let string = "abcd".yk.localized
複製代碼
第二種實現方式: 1.類型協議 2.命名空間協議 3.協議拓展app
/// 類型協議
protocol TypeWrapperProtocol {
associatedtype WrappedType
var wrappedValue: WrappedType { get }
init(value: WrappedType)
}
struct NamespaceWrapper<T>: TypeWrapperProtocol {
let wrappedValue: T
init(value: T) {
self.wrappedValue = value
}
}
複製代碼
/// 命名空間協議
protocol NamespaceWrappable {
associatedtype WrapperType
var jx: WrapperType { get }
static var jx: WrapperType.Type { get }
}
extension NamespaceWrappable {
var jx: NamespaceWrapper<Self> {
return NamespaceWrapper(value: self)
}
static var jx: NamespaceWrapper<Self>.Type {
return NamespaceWrapper.self
}
}
複製代碼
協議拓展函數
// 遵照命名空間協議
extension UIColor: NamespaceWrappable {}
// 協議拓展
extension TypeWrapperProtocol where WrappedType == UIColor {
/// 用自身顏色生成UIImage
var image: UIImage? {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(wrappedValue.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
}
// 使用
let image = UIColor.blue.jx.image
複製代碼
第三種方式類嵌套:ui
class Com {
class Test {
}
}
// 使用
let test = Com.Test()
複製代碼