Swift通过字符串调用类函数或属性
发布时间:2020-12-14 05:32:53 所属栏目:百科 来源:网络整理
导读:我有这门课 class Foo{ public class func barFunction(){} public class func barFunction2(){} public class func barFunction3(){}} 目前我有一个开关功能来确定要调用哪个bar方法 switch bar{ case "bar": Foo.barFunction(param:Double) case "bar2": F
我有这门课
class Foo{ public class func barFunction(){} public class func barFunction2(){} public class func barFunction3(){} } 目前我有一个开关功能来确定要调用哪个bar方法 switch bar{ case "bar": Foo.barFunction(param:Double) case "bar2": Foo.barFunction2(param:Double) case "bar3": Foo.barFunction3(param:Double) default: return } 如果我可以通过连接字符串来组成条形函数的名称并且只是通过字符串名称调用方法,那么整个过程会容易得多. 我已经在Swift中看到了,闭包是可行的方法,但我无法弄清楚闭包如何使它比开关操作更容易. 编辑:为了清楚,我想通过名称调用类func参数(字符串) 编辑(2):我需要它像这样工作,因为我有某些类型的数据库对象,以及特殊类或在屏幕上绘制这些对象的特殊方法.当我从数据库中获取一个对象时,我将其类型作为字符串,当前我正在使用switch语句来确定它将如何绘制. public class func getColors(iconType:String)->UIColor?{ switch iconType{ case "type1": return Assets.type1Color case "type2": return Assets.type2Color case "type3": return Assets.type3Color case "type4": return Assets.type4Color ... default: return nil } } 我觉得它是多余的,通过使用字符串来获取变量或函数可以简化它.如果还有其他办法,请告诉我.
您可以使用NSTimer一次调用选择器:
NSTimer.scheduledTimerWithTimeInterval(0,target: self,selector: Selector("barFunction"),userInfo: nil,repeats: false) 另一个更优雅的解决方 使用闭包和字典: let options = [ "bar1": { Foo.barFunction1() },"bar2": { Foo.barFunction2() },"bar3": { Foo.barFunction3() } ] // Ways of calling the closures options["bar2"]!() options["bar1"]?() let key = "bar3" if let closure = options[key] { closure() } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |