Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift function returning an Array

Tags:

arrays

ios

swift

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 <>

like image 635
pete Avatar asked Jul 07 '15 12:07

pete


2 Answers

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> {}
like image 179
Kirsteins Avatar answered Sep 21 '22 14:09

Kirsteins


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] {

}
like image 44
Valentin Avatar answered Sep 22 '22 14:09

Valentin