swift function returning an Array swift function returning an Array swift swift

swift function returning an Array


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


thanks all (especially Kirsteins). So I've come up with this example that works well and looks logical:

func myArrayFunc(inputArray:Array<String>) -> Array<String>{var newArray = inputArray// do stuff with newArrayreturn newArray}