iOS Swift Pass Closure as Property?

爱⌒轻易说出口 提交于 2019-11-30 01:55:04

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!")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!