Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of functions in Swift

How can I store an array of functions to callback later in an array like in JavaScript? Any and AnyObject type cannot hold functions with different types of method signatures.

like image 404
Encore PTL Avatar asked Jun 25 '14 21:06

Encore PTL


People also ask

What is the use of array in Swift function?

Arrays are one of the most commonly used data types in an app. You use arrays to organize your app's data. Specifically, you use the Array type to hold elements of a single type, the array's Element type. An array can store any kind of elements—from integers to strings to classes.

How do you pass an array to a function in Swift?

An array is an ordered collection which is used to store same type of data. It can be mutable or immutable. Swift allows you to pass an array in the function. To do so we just si mple declare a function with array type parameters.

Can a function return an array in Swift?

Swift's functions have a single return type, such as Int or String , but that doesn't mean we can only return a single value. In fact, there are two ways we can send back multiple pieces of data: Using a tuple, such as (name: String, age: Int) Using some sort of collection, such as an array or a dictionary.

How are arrays stored in Swift?

In Swift, we have a datatype ContiguousArray that ensures our array is stored in a contiguous area of memory.


2 Answers

You can use an enum to put various functions into the Array and then extract the functions with a switch.

    enum MyFuncs {         case Arity0 ( Void -> Void )         case Arity2 ( (Int, String) -> Void)     }      func someFunc(n:Int, S:String) { }     func boringFunc() {}     var funcs = Array<MyFuncs>()     funcs.append(MyFuncs.Arity0(boringFunc))     funcs.append( MyFuncs.Arity2(someFunc))      for f in funcs {         switch f {         case let .Arity0(f):             f()  // call the function with no arguments         case let .Arity2(f):             f(2,"fred") // call the function with two args         }     } 
like image 91
Bruce1q Avatar answered Oct 05 '22 10:10

Bruce1q


Note: this answer is for Swift versions 1.0 and lower.

Functions that have different parameters and return types are of a different type so they can't be stored in an array together. They also don't conform to the Any or AnyObject protocols.

If you have functions with the same parameters though you can work around that. Even though the functions below return a tuple of Double and an Int, they can both be defined as () -> Any function types.

func func1 () -> Int {     return 1 } func func2 () -> (Double, Double){     return (2, 3) } var a: () -> Int = func1 var b: () -> (Double, Double) = func2  var arr: Array< () -> Any> = [a, b] 
like image 31
Connor Avatar answered Oct 05 '22 10:10

Connor