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 closuresoptions["bar2"]!()options["bar1"]?()let key = "bar3"if let closure = options[key] { closure()}总结
以上是内存溢出为你收集整理的Swift通过字符串调用类函数或属性全部内容,希望文章能够帮你解决Swift通过字符串调用类函数或属性所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)