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.
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.
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.
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.
In Swift, we have a datatype ContiguousArray that ensures our array is stored in a contiguous area of memory.
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 } }
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With