iOS Swift Pass Closure as Property?

后端 未结 1 1533
后悔当初
后悔当初 2020-12-25 13:17

Let\'s say I have a custom UIView, lets call it MyCustomView. Inside this view is a UITextField property. Suppose my goal is to be able to create an instance of MyCustomView

相关标签:
1条回答
  • 2020-12-25 13:51

    Sure, you can do this. Swift has first class functions, so you are able to do things like directly pass functions around like variables. Keep in mind, functions themselves are in fact closures behind the scenes. Here's a basic example:

    class MyClass {
        var theClosure: (() -> ())?
    
        init() {
            self.theClosure = aMethod
        }
    
        func aMethod() -> () {
            println("I'm here!!!")
        }
    }
    
    
    let instance = MyClass()
    if let theClosure = instance.theClosure {
        theClosure()
    }
    
    instance.theClosure = {
        println("Woo!")
    }
    instance.theClosure!()
    

    And here is the same example using closures that can take a String parameter.

    class MyClass {
        var theClosure: ((someString: String) -> ())?
    
        init() {
            self.theClosure = aMethod
        }
    
        func aMethod(aString: String) -> () {
            println(aString)
        }
    }
    
    let instance = MyClass()
    if let theClosure = instance.theClosure {
        theClosure(someString: "I'm the first cool string")
    }
    
    instance.theClosure = {(theVerySameString: String) -> () in
        println(theVerySameString)
        someThingReturningBool()
    }
    instance.theClosure!(someString: "I'm a cool string!")
    
    0 讨论(0)
提交回复
热议问题