迭代Swift扩展中的可用类?

时间:2018-05-11 16:24:04

标签: ios swift class swift4 extension-methods

我之前从未尝试过的东西,但是我有一个扩展,如下所示(为简洁起见),我希望能够在代码中绘制出每种可用的颜色。我之前从未尝试过这种方法,也无法将正确的搜索词汇集中在一起。思想,指针?

我想以某种方式获得let availableColors: [UIColor] = magicalFunctionHere(pointing扩展... ....

我想我必须创建自己的函数并在扩展中找到的UIColors中手动ram。我宁愿自动化这个。

extension UIColor {
    class func firstColor ( alpha: CGFloat = 1.0 ) -> UIColor {
        return  UIColor.init ( red: 139.0/255.0, green: 322.0/255.0, blue: 405.0/255.0, alpha: alpha )
    }

    class func secondColor ( alpha: CGFloat = 1.0 ) -> UIColor {
        return  UIColor.init ( red: 225.0/255.0, green: 139.0/255.0, blue: 127.0/255.0, alpha: alpha )
    }
}

1 个答案:

答案 0 :(得分:2)

以下是使用Obj-C运行时方法的代码(注意@objc前缀,它们需要使运行时“看到”你的方法):

import Foundation
import XCPlayground
import UIKit

extension UIColor {
    @objc class func fancyColorFirst ( alpha: CGFloat = 1.0 ) -> UIColor {
        return UIColor.red.withAlphaComponent(alpha)
    }

    @objc class func fancyColorSecond ( alpha: CGFloat = 1.0 ) -> UIColor {
        return UIColor.blue.withAlphaComponent(alpha)
    }
}

func methods(in c: AnyClass, where condition: (String) -> Bool ) -> [String] {
    var count: UInt32 = 0
    guard let foundMethods = class_copyMethodList(object_getClass(c), &count) else { return [] }

    let totalMethods = Int(count)
    var matches = [String]()

    for index in 0..<totalMethods {
        let method: Method = foundMethods[index]
        let selector: Selector = method_getName(method)
        let methodName = String(_sel:selector)
        if condition(methodName) {
            matches.append(methodName)
        }
    }
    return matches
}

print(methods(in: UIColor.self, where: { $0.hasPrefix("fancyColor")}))