Im learning Swift and I can understand how to create a simple function that takes in an Array and returns an Array. Heres my code:
func myArrayFunc(inputArray:Array) -> Array{
var newArray = inputArray
// do stuff with newArray
return newArray
}
The red error I get is: Reference to generic type 'Array" requires arguments in <>
In Swift Array
is generic type, so you have to specify what type array contains. For example:
func myArrayFunc(inputArray:Array<Int>) -> Array<Int> {}
If you want your function to be generic then use:
func myArrayFunc<T>(inputArray:Array<T>) -> Array<T> {}
If you don't want to specify type or have generic function use Any
type:
func myArrayFunc(inputArray:Array<Any>) -> Array<Any> {}
Depends on what is it exactly you want to do. If you want a specialized function that takes an array of a specific type MyType, then you could write something like:
func myArrayFunc(inputArray: [MyType]) -> [MyType] {
// do something to inputArray, perhaps copy it?
}
If you want a generic array function, then you have to use generics. This would take an array of generic type T and return an array of generic type U:
func myGenericArrayFunc<T, U>(inputArray: [T]) -> [U] {
}
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