Swift通过字符串

时间:2015-05-17 10:58:28

标签: string function swift

我有这个班级

class Foo{
     public class func barFunction(){}
     public class func barFunction2(){}
     public class func barFunction3(){}
}

目前我有一个开关功能来确定调用哪种方法

switch bar{
      case "bar": Foo.barFunction(param:Double)
      case "bar2": Foo.barFunction2(param:Double)
      case "bar3": Foo.barFunction3(param:Double)
      default: return
}

如果我可以通过连接字符串来组成bar函数的名称并且只是通过字符串名称调用方法,那么整个事情会容易得多。

我已经读到,在Swift中,闭包是可行的方法,但我无法弄清楚闭包会如何使它比开关操作更容易。

编辑:为了清楚起见,我想用名称(字符串)>使用参数调用类功能

编辑(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
    }
}

我觉得它是多余的,并且可以通过使用字符串来获取变量或函数来简化它。如果还有其他办法,请告诉我。

1 个答案:

答案 0 :(得分:8)

您可以使用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()
}