Reputation: 3050
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 <>
Upvotes: 18
Views: 66961
Reputation: 27345
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> {}
Upvotes: 39
Reputation: 3050
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 newArray
return newArray
}
Upvotes: 1
Reputation: 1741
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] {
}
Upvotes: 8
Reputation: 10091
This should do it:
func myArrayFunc<T>(inputArray:Array<T>) -> Array<T> {
var newArray = inputArray
// do stuff with newArray
return newArray
}
You declare the generic type T
, which is just a placeholder. Because it has no requirements T
can be replaced by any type (when the function is called). So your function could be called like this:
myArrayFunc([1, 2, 3])
or this:
myArrayFunc(["a", "b", "c"])
The preferred syntax is generally [T]
rather than Array<T>
, though. (although both are correct)
func myArrayFunc<T>(inputArray: [T]) -> [T] {
var newArray = inputArray
// do stuff with newArray
return newArray
}
Upvotes: -1
Reputation: 777
Try this
var test = doArray([true,true,true])
test.count
func doArray(arr : [AnyObject]) -> [AnyObject] {
var _arr = arr
return _arr
}
Upvotes: -1
Reputation: 27434
There is no such thing as an Array
in Swift, but there are arrays of a certain type, so you should give the function a generic type, like in:
func myArrayFunc<T>(inputArray:Array<T>) -> Array<T>{
// do what you want with the array
}
and then call it by instantiating T to a specific type, and passing an array of such type.
Upvotes: 0