Swift call class function or property by string

后端 未结 1 1364
予麋鹿
予麋鹿 2020-12-21 06:32

I have this class

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


        
相关标签:
1条回答
  • 2020-12-21 06:59

    You can use NSTimer to call a selector once:

    NSTimer.scheduledTimerWithTimeInterval(0, target: self, selector: Selector("barFunction"), userInfo: nil, repeats: false)
    

    Another more elegant solution

    Using closures and dictionary:

    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()
    }
    
    0 讨论(0)
提交回复
热议问题