0

I tried making an array of functions and Xcode did not let me. This is the error I get:

Value of type '(ViewController) -> () -> (ViewController)' has no member 'firstFunc'

Essentially I need to know how array of functions are made in order to randomly call them later.

let randomFunc = [self.firstFunc(),self.secondFunc(),self.thirdFunc()]

func firstFunc(){
}

func secondFunc(){
}

func thirdFunc(){
}

2 Answers 2

1

I think you need to only give the name of the function, currently you are calling the functions,

And if you want to use self as well you can do something like this: (you need to make this property lazy var to use self)

class foo {
        lazy var randomFunc = [self.firstFunc,self.secondFunc,self.thirdFunc]
        func firstFunc(){

                print(123)
        }

        func secondFunc(){


        }

        func thirdFunc(){


        }
}

Usage:

let f = foo()
f.randomFunc[0]()  // prints 123
Sign up to request clarification or add additional context in comments.

2 Comments

Hey thanks that worked, it let me create the array but now I don't know how to call it.
@Alex Glad , I could help
0
lazy var array = [self.fun1,self.fun2,self.fun3]

Functions:

func fun1() {
    print("func1")
}
func fun2() {
    print("func2")

}
func fun3() {
    print("func3")

}

Usage:

self.array[0]()

Prints:

func1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.