Dăn*_*ian 2 string function swift
我有这门课
class Foo{
public class func barFunction(){}
public class func barFunction2(){}
public class func barFunction3(){}
}
Run Code Online (Sandbox Code Playgroud)
目前我有一个开关功能来确定要调用哪个bar方法
switch bar{
case "bar": Foo.barFunction(param:Double)
case "bar2": Foo.barFunction2(param:Double)
case "bar3": Foo.barFunction3(param:Double)
default: return
}
Run Code Online (Sandbox Code Playgroud)
如果我可以通过连接字符串来组成条形函数的名称并且只是通过字符串名称调用方法,那么整个过程会更容易.
我已经在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
}
}
Run Code Online (Sandbox Code Playgroud)
我觉得它是多余的,通过使用字符串来获取变量或函数可以简化它.如果还有其他方法可以做到这一点,请告诉我.
您可以使用NSTimer一次调用选择器:
NSTimer.scheduledTimerWithTimeInterval(0, target: self, selector: Selector("barFunction"), userInfo: nil, repeats: false)
Run Code Online (Sandbox Code Playgroud)
使用闭包和字典:
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()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3787 次 |
| 最近记录: |