Swift通过字符串调用类函数或属性

我有这门课
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()
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...