Swift,与方法名称相同的变量 [英] Swift, variable with same as a method name

查看:14
本文介绍了Swift,与方法名称相同的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个:

var formVC:UIViewController!

我也想拥有一个名为:

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

我知道在 OBJC 中它有效,但我没有看到在 Swift 中执行此操作的方法.有没有办法解决这个问题,或者我不理解 Swift 中明显的架构/概念变化?

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?

提前致谢.

推荐答案

这在 ObjC 中是个坏主意,在 Swift 中是非法的.考虑其中一些情况:

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()

在这种情况下 x.value 是什么?是 Int 还是 () ->整数?将类的方法视为闭包是合法且有用的.

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() // ????

Swift 应该使用属性 value 然后调用它吗?还是应该调用value() 方法?闭包作为属性是完全合法的.

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

同样的限制实际上存在于 ObjC 中.你也不能创建一个与方法冲突的合成属性(如果它们有不同的类型;如果它们有相同的类型,ObjC 将默默地不合成访问器).您正在考虑 Swift 属性,就像它们等同于 ObjC 的 ivars,但这是不对的.Swift 的属性等同于 ObjC 的 属性(即访问 ivars 的方法).您无法访问 Swift 中的底层 ivars.

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 type, 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.

这篇关于Swift,与方法名称相同的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆