如何在Swift中调用函数内部的函数

时间:2021-08-31 16:45:21
@IBAction func first(sender: AnyObject) {
    println("Hello World")
}

@IBAction func second(sender: Anyobject) {
// I need to call function first here. 
}

I need to use one function inside another, because the sender type is Anyobject, I don't know how to call it.

我需要在另一个内部使用一个函数,因为发件人类型是Anyobject,我不知道如何调用它。

2 个解决方案

#1


Have you tried

你有没有尝试过

func first(){
    println("Hello World")
}

@IBAction func second(sender: AnyObject) {
    first()
}

#2


If you are sure about the type of control,it should be UIControl object likeUIButton,UISegmentControl etc, then change the sender to that type.

如果您确定控件的类型,它应该是UIControl对象,如UIButton,UISegmentControl等,然后将发件人更改为该类型。

If both function's parameter are same you can do like

如果两个函数的参数相同,您可以这样做

@IBAction func second(sender: UIButton) {//it sure that you are clikcing UIButton
    self.first(sender)//if here also a button, else create the control and pass.
}

But why you want first function as @IBAction? If it is not attached to any control please make it as normal function

但是为什么你想要第一个函数@IBAction?如果没有任何控制,请将其作为正常功能

#1


Have you tried

你有没有尝试过

func first(){
    println("Hello World")
}

@IBAction func second(sender: AnyObject) {
    first()
}

#2


If you are sure about the type of control,it should be UIControl object likeUIButton,UISegmentControl etc, then change the sender to that type.

如果您确定控件的类型,它应该是UIControl对象,如UIButton,UISegmentControl等,然后将发件人更改为该类型。

If both function's parameter are same you can do like

如果两个函数的参数相同,您可以这样做

@IBAction func second(sender: UIButton) {//it sure that you are clikcing UIButton
    self.first(sender)//if here also a button, else create the control and pass.
}

But why you want first function as @IBAction? If it is not attached to any control please make it as normal function

但是为什么你想要第一个函数@IBAction?如果没有任何控制,请将其作为正常功能