Swift, variable with same as a method name

2019-02-13 12:43发布

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.

2条回答
Melony?
2楼-- · 2019-02-13 13:22

This was a bad idea in ObjC, and it's 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'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:

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

Should Swift use the property value and then call it? Or should it call the method value()? 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.

查看更多
趁早两清
3楼-- · 2019-02-13 13:23

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 and foo() 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 like formViewController and the function something like createFormViewController.

var foo = 0

func foo() {} // Error: Invalid redeclaration of foo

func foo(string: String) {} // No error

and if you are only using the function to set the variable, use computed properties instead:

lazy var formViewController: UIViewController! {
    return UIViewController()
}
查看更多
登录 后发表回答