gpt4 book ai didi

ios - 迭代 Swift 扩展中的可用类?

转载 作者:搜寻专家 更新时间:2023-11-01 07:02:30 26 4
gpt4 key购买 nike

这是我以前从未尝试过的事情,但我有一个扩展,如下所示(为简洁起见,删减),我希望能够在代码中绘制出每种可用的颜色。我以前从未尝试过,无法将正确的搜索词组合在一起甚至接近。想法,指点?

我想得到 let availableColors: [UIColor] = magicalFunctionHere(pointing to extension somehow) ....

我想我将不得不创建自己的函数并在扩展中找到的 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 )
}
}

最佳答案

这是使用 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")}))

关于ios - 迭代 Swift 扩展中的可用类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50296484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com