对不起,这些问题
我在swift中有4个关于Selector的问题.
第一个问题
我想知道在swift中使用selector的正确方法是什么
closeBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: Selector("closeBarButtonItemClicked:"));
Run Code Online (Sandbox Code Playgroud)
VS
closeBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: "closeBarButtonItemClicked:");
Run Code Online (Sandbox Code Playgroud)
我们应该立即使用Selector("methodName:")或"methodName:"吗?
两种方式都有效但哪一种方法正确?
第二个问题
我们如何在Swift中使用参数调用函数?假设我想调用这样的函数
func methodName(parameterOne : String, parameterTwo: String)
Run Code Online (Sandbox Code Playgroud)
第三个问题
我们如何在swift中使用Selector调用类型方法?甚至可能吗?
class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
Run Code Online (Sandbox Code Playgroud)
第四个问题
在Selector中函数名后面的冒号的目的是什么?
Nat*_*ook 17
@ ad121的答案很棒 - 只想在#1中添加一些上下文:
该Selector类型已在Swift中扩展为StringLiteralConvertible.每当Selector期望实例时,您可以改为给出一个字符串文字,并Selector为您创建一个实例.这意味着您还可以Selector手动从字符串文字创建实例:
let mySelector: Selector = "methodName:withParameter:"
Run Code Online (Sandbox Code Playgroud)
请注意,这并不意味着a String可以与a互换使用Selector- 这只适用于字符串文字.以下将失败:
let methodName = "methodName:withParameter:"
let mySelector: Selector = methodName
// error: 'String' is not convertible to 'Selector'
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您需要自己实际调用Selector构造函数:
let methodName = "methodName:withParameter:"
let mySelector = Selector(methodName)
Run Code Online (Sandbox Code Playgroud)
ad1*_*121 14
问题1:我认为没有一个正确的方法.我个人更喜欢第二种方式,但两者都有效,所以我认为这不重要.
问题2:我刚读过你的问题.我认为你的意思是如何在选择器中调用它.我相信的选择器会是,"methodName:parameterTwo:"但我不是肯定的,因为带有两个参数的选择器可能应该有一个外部参数名称放在选择器中,其中parameterTwo在我的答案中.
旧问题2答案(编辑之前):您可以将该功能称为" methodName(variable1, parameterTwo: variable2).如果您想让他们在呼叫中说出参数名称,您可以设置标题" methodName(calledVarName parameterOne: String, calledVarName2 parameterTwo: String).这将被称为methodName(calledVarName: variable1, calledVarName2: variable2).您还可以将标头定义为methodName(#parameterOne: String, #parameterTwo: String).这将被称为methodName(parameterOne: variable1, parameterTwo: variable2).在此处阅读更多内容:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html
问题3:我不能肯定地说,但我认为没有办法为此制作一个选择器.如果有,我认为它将是"someTypeMethod"
旧问题3答案(编辑之前):您可以通过调用此方法SomeClass.someTypeMethod().
问题4:冒号表示函数头有参数.所以"function1:"对应于func function1(someParameterName: AnyObjectHere)while "function1"对应func function1().
| 归档时间: |
|
| 查看次数: |
10619 次 |
| 最近记录: |