无法转换'NSObject - >类型的值() - > PostFeed'到预期的参数类型'AnyObject?' [英] Cannot convert value of type 'NSObject -> () -> PostFeed' to expected argument type 'AnyObject?'
问题描述
我按以下方式添加 UISwitch
:
let anonSwitch : UISwitch = {
let mySwitch = UISwitch()
mySwitch.on = false
mySwitch.setOn(false, animated: false);
mySwitch.tintColor = UIColor(red: (69/255.0), green: (209/255.0), blue: (153/255.0), alpha: 1.0)
mySwitch.addTarget(self, action: #selector(handleAnonSwitch), forControlEvents: .ValueChanged)
return mySwitch
}()
现在我在 mySwitch.addTarget
中的 self
关键字上收到以下错误消息:
Now I'm getting the following error message on the self
keyword in mySwitch.addTarget
:
Cannot convert value of type 'NSObject -> () -> PostFeed' to expected argument type 'AnyObject?'
我使用 self
在我的所有其他 addTarget
函数中 UIButton
我从未遇到过这个错误
I use self
in all my other addTarget
functions for UIButton
and I never encounter this error
推荐答案
将让
更改为 lazy var
。
我不确定编译器到底在想什么(或者它的疯狂错误信息来自哪里),但我的猜测是:
I'm not sure exactly what the compiler is thinking (or where its crazy error message is coming from), but my guess is this:
在Swift中,必须初始化 let
的变量才能使用 self
。其中一个原因是编译器无法验证 addTarget(action:forControlEvents:)
是否会尝试调用 anonSwitch()
关于 target
获取的内容,或执行其他操作,例如访问将在 anonSwitch <之后初始化的其他变量
,这取决于为此对象完成的初始化。
In Swift, variables which are let
have to be initialized before you can use self
. One reason for this is that the compiler can't verify that addTarget(action:forControlEvents:)
isn't going to try to call anonSwitch()
on whatever it gets for target
, or do something else, like access a different variable that would be initialized after anonSwitch
, that depends on initialization having completed for this object.
使用 lazy var
表示编译器可以验证分配给 anonSwitch <的值在
self
是有效对象之前,将不会访问/ code>,因为无法调用 anonSwitch
直到该类的所有其他成员都已初始化。
Using lazy var
means that the compiler can verify that the value assigned to anonSwitch
won't be accessed before self
is a valid object, because it won't be possible to call anonSwitch
until all other members of the class have been initialized.
这篇关于无法转换'NSObject - >类型的值() - > PostFeed'到预期的参数类型'AnyObject?'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!