Initialize Closure in Swift

Initialize closure in Swift

Simple example:

class TestClass {
var myClosure: (Int) -> ()
init(){
func myFunc(_:Int) {}
self.myClosure = myFunc
}
}

Or use an anonymous function:

class TestClass {
var myClosure: (Int) -> ()
init(){
self.myClosure = {_ in}
}
}

Or you could do the initialization as part if the declaration of myClosure:

class TestClass {
var myClosure : (Int) -> () = {_ in}
init(){
}
}

But if you don't have the value of myClosure at initialization time, why not make it an Optional?

class TestClass {
var myClosure: ((Int) -> ())?
init(){
}
}

How to initialise closure variable in swift?

You can initialize closure variable as,

init(onselecteditem : @escaping (Int) -> Void) {
self.onSelectedItem = onselecteditem
}

Initialize closure in Swift

Simple example:

class TestClass {
var myClosure: (Int) -> ()
init(){
func myFunc(_:Int) {}
self.myClosure = myFunc
}
}

Or use an anonymous function:

class TestClass {
var myClosure: (Int) -> ()
init(){
self.myClosure = {_ in}
}
}

Or you could do the initialization as part if the declaration of myClosure:

class TestClass {
var myClosure : (Int) -> () = {_ in}
init(){
}
}

But if you don't have the value of myClosure at initialization time, why not make it an Optional?

class TestClass {
var myClosure: ((Int) -> ())?
init(){
}
}

Property Initialization with closures

This is not a retain cycle because self is not what you think it is :)

Properties with initial value are "executed" even before any initializer runs, and for those properties self points to a higher order function of this type:

(TestClass) -> () -> TestClass

So you don't really access the instance, but rather you access a static-like method that does the initialization of all properties that have a default value. This is why you don't have a retain cycle.

addTarget accepts an Any? value for it's first argument, so this violates no type rules so the compiler doesn't complain that you don't pass a NSObject instance there.

Checking the later behaviour - e.g. what happens if the button is added to the UI hierarchy and is tapped, reveals something interesting: the runtime sees that you passed a non-object as a target and sets null values for target and action:

Sample Image

How can you initialize a struct with a closure parameter like this?

This works just like any function whose last parameter is a function. Trailing closure syntax is trailing closure syntax. The fact that the function is an initializer changes nothing.

So let me build up to it in stages. You know you can say:

func myfunc(whatever: () -> ()) {}
myfunc {}

Okay, but now let's make it a static method:

struct S {
static func myfunc(whatever: () -> ()) {}
}
S.myfunc {}

OK, but init is a static method — it's just a static method whose name you are allowed to omit:

struct S {
let whatever: () -> ()
}
S {} // meaning S.init {}

SwiftUI view, initialize closure with struct member says 'self' used before all stored properties are initialized

Try the following (viewModel is reference type, so you can manipulate with it as temporary variable)

init(currentSelectedTab: Tab) {
let vm = TabScreenViewModel(
input: TabScreenInput(
onStart: PassthroughSubject(),
onTabClick: PassthroughSubject()
)
)
self.viewModel = vm
onTabItemTap = {
[vm](tab: Tab) -> Void in
vm.input.onTabClick.send(tab)
}
}

Accessing self in initializing closure

This quoted example of the Migration Guide is misleading because it's related to a global variable.

The closure of a instance let constant is called (once) immediately when the class is initialized. That's the reason why it cannot use other variables declared on the same level.

What you can do is to initialize initialize (the variable name is not the best one ;-) ) lazily. The closure is also called only once but – as the guide describes – only the first time (when) it is used.

class SomeClass {
let other = SomeOtherClass()

lazy var initialize : () = {
let test = self.other
test.doSomething()
}()

func doSomething() {
// initialize will only be called once
_ = initialize
}
}

Swift - `self` in variable initialization closure

It works in NSObject subclasses because NSObject (or rather NSObjectProtocol) declares method self. That method is also available on metatypes (which are also NSObject instances) and therefore you can call it in static context.

The fact that it actually works on UIButton is probably a quirk of the compiler and the fact that UIButton accepts Any? as target.

Don't use it, it's not how it's intended to work.

See the bug SR-4559

Swift: Closure as a init argument in a class variable

Here is as close as I could get to what you wanted by fiddling around in a playground. I had to change the types to match what you were passing to Calculator

class Calculator {
private let estimateChanged:() -> Void

init(_ estimateChanged:() -> Void) {
self.estimateChanged = estimateChanged
}
}

class AnotherClass {
lazy var callback: () -> Void = { [unowned self] in
self.loadEstimate()
}
var calculator: Calculator?

// viewDidLoad in the case of a view controller
init() {
calculator = Calculator(callback)
}

func loadEstimate() {}
}

It is obviously not exactly what you wanted but it compiles. There seem to be issues when trying to refer to self in an un-initialized object (even when it seems you should be able to because you specify lazy and weak or unowned etc)



Related Topics



Leave a reply



Submit