I have a :
var formVC:UIViewController!
I'm also trying to have a function named:
func formVC()->UIViewController{....}
I know in OBJC it worked, but I'm not seeing a way to do this in Swift. Is there a way to go about this, or am i not understanding an obvious architectural/conceptual change in Swift?
Thanks in advance.
This was a bad idea in ObjC, and it's illegal in Swift. Consider some of these cases:
What is
x.value
in this case? Is itInt
or is it() -> Int
? It's legal and useful to treat the methods of classes as if they were closures.What if we're even more tricky, and do this:
Should Swift use the property
value
and then call it? Or should it call the methodvalue()
? Closures are completely legal as properties.The same restriction actually exists in ObjC. You couldn't create a synthesized property that conflicted with a method either (if they had different types; if they had the same time, ObjC would silently not synthesize the accessor). You're thinking of Swift properties like they're equivalent to ObjC's ivars, but that's not right. Swift's properties are equivalent to ObjC's properties (i.e. the methods that access the ivars). You have no access to the underlying ivars in Swift.
In Swift, you cannot name a variable and a function the same thing if no parameters are passed. Although we call them in different ways (
foo
for a variable andfoo()
for a function) we will get an invalid redeclaration of foo. The compiler treats the variable as if it has no parameters like the function does. However, using parameters, you can name a function and a variable the same thing, although I would advise you not to. In this case you should try to name the variable and the function something that describes what they are and/or what they do to make your code more readable by others. I would suggest naming the variable something likeformViewController
and the function something likecreateFormViewController
.and if you are only using the function to set the variable, use computed properties instead: