Swift, a variable with a method name

I have:

var formVC:UIViewController! 

I am also trying to create a function called:

 func formVC()->UIViewController{....} 

I know that in OBJC this worked, but I see no way to do this in Swift. Is there a way to do this, or do I not understand the obvious architectural / conceptual changes in Swift?

Thanks in advance.

+6
source share
2 answers

It was a bad idea in ObjC, and it was illegal in Swift. Consider some of these cases:

 class X { var value : Int = 0 func value() -> Int { return 1 } } let x = X() 

What is x.value in this case? Is it Int or is it () -> Int ? It is legal and useful to treat class methods as closures.

What if we are even more complex and do this:

 class X { let value: () -> Int = { 2 } func value() -> Int { return 1 } } let x = X() let v = x.value() // ???? 

Should Swift use the value property and then call it? Or should it call the value() method? Closures are completely legal as properties.

The same restriction exists in ObjC. You could not create a synthesized property that would contradict the method (if they had different types, if they had the same time, ObjC would be silent to synthesize the accessor). You are thinking of Swift properties similar to ObjC ivars, but it is not. Swift properties are equivalent to ObjC properties (i.e. ivars access methods). You do not have access to the basic ivars in Swift.

+6
source

In Swift, you cannot name a variable and function the same if parameters are not passed. Although we call them differently ( foo for a variable and foo() for a function), we get an invalid fix for foo. The compiler processes the variable as if it has no parameters similar to a function. However, using the parameters, you can name the function and variable the same, although I would advise you not to. In this case, you should try to name the variable and function what describes what they represent and / or what they do to make your code more readable by others. I would suggest calling the variable something like formViewController , and a function like createFormViewController .

 var foo = 0 func foo() {} // Error: Invalid redeclaration of foo func foo(string: String) {} // No error 

and if you use only a function to set a variable, use calculated properties instead:

 lazy var formViewController: UIViewController! { return UIViewController() } 
+2
source

Source: https://habr.com/ru/post/983715/


All Articles